From 21dbcf6307e90be1d49ac4f438aaad74dcd0f3c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 20:16:54 -0800 Subject: [PATCH 01/28] Links: list and manage linked art in symbols, graph designs, patterns and masks by id Linked images and placed documents kept only in symbols, graph designs, pattern swatches or opacity masks now have ids of their own. links.list lists them after the layers' own, one row per stored object, with an owner naming what holds them; links.check, the missing, modified and updated files reported on open, the link watch and links.findFiles report them by id; relink (All Instances included), update, embed, placementOptions, info and image.info act on them. links.goTo on one clears the selection and returns onCanvas: false with its owner, and the Links panel says the link has no place on the canvas. - Document::visit_stored, stored_node and stored_node_mut find objects in every stored art. fix_next_id counts their ids and gives an object there whose id is 0, past the id range or already used a new one, updating Objects on Path references to renamed children. - Copies of masked objects give the mask art new ids, and symbols and patterns that placed art brings from another document take ids of the document they join. - The Links panel picks such rows in the panel itself, drops the pick when the canvas selection changes, and draws their thumbnails from a lookup made once per list refresh. Select by Link Status leaves them out, as it cannot select them. --- crates/doc/src/document.rs | 9 +- crates/doc/src/document_guides.rs | 7 + crates/doc/src/lib.rs | 2 + crates/doc/src/stored_art.rs | 376 ++++++++++++++++++ crates/engine/src/cmd/linkfiles.rs | 12 +- crates/engine/src/cmd/links.rs | 203 ++++++---- crates/engine/src/cmd/place.rs | 3 +- crates/engine/src/cmd/place/adopt.rs | 3 + crates/engine/src/cmd/place/document.rs | 8 +- crates/engine/src/tests/links.rs | 204 +++++++++- crates/engine/src/tests/linkspanel.rs | 2 +- crates/engine/src/tests/linkwatch.rs | 24 ++ crates/engine/src/tests/place.rs | 27 ++ .../ui-egui/src/addons/select/link_status.rs | 17 +- .../src/addons/select/link_status/tests.rs | 21 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/links.rs | 131 +++++- crates/ui-egui/src/panels/tests_links.rs | 46 +++ docs/mcp.md | 20 +- docs/target-app-parity.md | 1 + 41 files changed, 1031 insertions(+), 107 deletions(-) create mode 100644 crates/doc/src/stored_art.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 708d0aee03..057a9df6a6 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -286,7 +286,9 @@ impl Document { self.next_id = self.next_id.max(id); } - /// Ensure `next_id` is above every id in the tree (after deserializing foreign data). + /// Ensure `next_id` is above every id in the tree (after deserializing foreign data), then give + /// the objects outside the layer tree (opacity-mask art, symbols, graph designs and patterns) + /// whose id is missing or already taken a new one, so each stored object has an id of its own. pub fn fix_next_id(&mut self) { // Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a // counter up there: new ids start under them and never reach them, where counting on from @@ -297,13 +299,12 @@ impl Document { max = max.max(id); } }; - for l in &self.layers { - l.walk(&mut |n| see(n.id.0)); - } + self.visit_stored(|n, _| see(n.id.0)); self.slices.iter().for_each(|s| see(s.id.0)); self.assets.iter().for_each(|a| see(a.id)); let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0); self.next_id = counter.max(max.saturating_add(1)); + self.renumber_stored_duplicates(); } /// Find a node anywhere in the tree. diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 4ec7aab1f6..14d0404bfc 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -554,6 +554,13 @@ impl Document { t.cached_baselines.clear(); t.cached_ink = None; } + // Opacity-mask art is stored art too: the copy's gets ids of its own. + if let Some(art) = n.extras().mask.as_ref().map(|m| Arc::clone(&m.art)) { + let art = Arc::new(self.reid(&art)); + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + m.art = art; + } + } let on_path = n.extras().objects_on_path.is_some(); let mut renamed = std::collections::HashMap::new(); if let Some(ch) = n.children_mut() { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 3c4bcc20a5..03c7da06c3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -141,6 +141,7 @@ mod graphic_style; mod guides; mod limits; mod records; +mod stored_art; mod units; pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS}; @@ -153,6 +154,7 @@ pub use guides::{GridPrefs, Guide, RulerMode}; use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; +pub use stored_art::{StoredPlace, StoredRoot}; pub use units::{ColorMode, Unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/doc/src/stored_art.rs b/crates/doc/src/stored_art.rs new file mode 100644 index 0000000000..e623e0ed0e --- /dev/null +++ b/crates/doc/src/stored_art.rs @@ -0,0 +1,376 @@ +//! Every object a document stores, wherever it is kept: in the layers, in opacity-mask art, and in +//! the art of symbols, graph designs and pattern swatches. [`Document::node`] finds objects in the +//! layer tree only; the lookups here find the others by their ids too, which +//! [`Document::fix_next_id`] keeps unique across all of them. + +use std::collections::HashSet; +use std::sync::Arc; + +use super::limits::MAX_NEXT_ID; +use super::{Document, Node, NodeId}; + +/// The art a stored object belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StoredRoot { + /// Layer `index` of [`Document::layers`]. + Layer(usize), + /// Symbol `index` of [`Document::symbols`]. + Symbol(usize), + /// Graph design `index` of [`Document::graph_designs`]. + GraphDesign(usize), + /// Object `art` of pattern swatch `pattern` of [`Document::patterns`]. + Pattern { pattern: usize, art: usize }, +} + +/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs +/// to (the innermost one when masks hold masks). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StoredPlace { + pub root: StoredRoot, + pub mask_of: Option, +} + +impl StoredPlace { + /// Is the object in the layer tree itself, where [`Document::node`] finds it and the canvas + /// draws it as itself? + pub fn in_layers(self) -> bool { + matches!(self.root, StoredRoot::Layer(_)) && self.mask_of.is_none() + } +} + +/// One step down from a node: to its child at an index, or to its opacity-mask art. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Step { + Child(usize), + Mask, +} + +/// `n` and everything below it with its place, the opacity-mask art right after the object it +/// masks, then the children. +fn visit<'a>(n: &'a Arc, place: StoredPlace, f: &mut dyn FnMut(&'a Arc, StoredPlace)) { + f(n, place); + if let Some(m) = &n.extras().mask { + visit(&m.art, StoredPlace { mask_of: Some(n.id), ..place }, f); + } + for c in n.children().into_iter().flatten() { + visit(c, place, f); + } +} + +/// The steps from `n` to the first node in [`visit`] order with id `id`, and the object whose mask +/// holds it last on the way. +fn find(n: &Node, id: NodeId, steps: &mut Vec, mask_of: &mut Option) -> bool { + if n.id == id { + return true; + } + if let Some(m) = &n.extras().mask { + steps.push(Step::Mask); + let before = *mask_of; + *mask_of = Some(n.id); + if find(&m.art, id, steps, mask_of) { + return true; + } + *mask_of = before; + steps.pop(); + } + for (i, c) in n.children().into_iter().flatten().enumerate() { + steps.push(Step::Child(i)); + if find(c, id, steps, mask_of) { + return true; + } + steps.pop(); + } + false +} + +/// The node `steps` below `n`. +fn at<'a>(mut n: &'a Arc, steps: &[Step]) -> Option<&'a Arc> { + for s in steps { + n = match s { + Step::Mask => &n.extras().mask.as_ref()?.art, + Step::Child(i) => n.children()?.get(*i)?, + }; + } + Some(n) +} + +/// The node `steps` below `n` to change, the nodes on the way copied when shared. +fn at_mut<'a>(mut n: &'a mut Arc, steps: &[Step]) -> Option<&'a mut Node> { + for s in steps { + let node = Arc::make_mut(n); + n = match s { + Step::Mask => &mut node.extras_if_any()?.mask.as_mut()?.art, + Step::Child(i) => node.children_mut()?.get_mut(*i)?, + }; + } + Some(Arc::make_mut(n)) +} + +/// Gives every node from `n` down that `fresh` names a new id from `next`, counting nodes in +/// [`visit`] order from `*count`; only the nodes on the way to one are copied. Each part below is +/// renumbered through a second handle, so a new pointer marks a change. +fn renumber(n: &mut Arc, fresh: &HashSet, count: &mut usize, next: &mut u64) { + let own = fresh.contains(count); + *count += 1; + let mask = n.extras().mask.as_ref().and_then(|m| { + let mut art = Arc::clone(&m.art); + renumber(&mut art, fresh, count, next); + (!Arc::ptr_eq(&art, &m.art)).then_some(art) + }); + let mut slots = vec![]; + // Children's new ids by their old ones, for an Objects on Path group, which names its path and + // members by id. An id another child keeps still names that child. + let mut renamed = std::collections::HashMap::new(); + let mut kept = HashSet::new(); + for (i, c) in n.children().into_iter().flatten().enumerate() { + let mut new = Arc::clone(c); + renumber(&mut new, fresh, count, next); + if new.id == c.id { + kept.insert(c.id); + } else { + renamed.insert(c.id, new.id); + } + if !Arc::ptr_eq(&new, c) { + slots.push((i, new)); + } + } + renamed.retain(|old, _| !kept.contains(old)); + if !own && mask.is_none() && slots.is_empty() { + return; + } + let node = Arc::make_mut(n); + if own { + node.id = NodeId(*next); + *next += 1; + } + if let (Some(art), Some(m)) = (mask, node.extras_if_any().and_then(|e| e.mask.as_mut())) { + m.art = art; + } + if let Some(children) = node.children_mut() { + for (i, c) in slots { + if let Some(slot) = children.get_mut(i) { + *slot = c; + } + } + } + if !renamed.is_empty() + && let Some(on_path) = node.extras_if_any().and_then(|e| e.objects_on_path.as_mut()) + { + on_path.rename(&renamed); + } +} + +impl Document { + /// The roots of the art kept outside the layers, each with its [`StoredRoot`]. + fn definition_roots(&self) -> impl Iterator, StoredRoot)> { + let symbols = self.symbols.iter().enumerate().map(|(i, s)| (&s.art, StoredRoot::Symbol(i))); + let designs = self.graph_designs.iter().enumerate().map(|(i, g)| (&g.art, StoredRoot::GraphDesign(i))); + let patterns = self + .patterns + .iter() + .enumerate() + .flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a }))); + symbols.chain(designs).chain(patterns) + } + + /// Every root of stored art: the layers, then the art of symbols, graph designs and patterns. + fn stored_roots(&self) -> impl Iterator, StoredRoot)> { + self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots()) + } + + /// The root `root` names, to change. + fn stored_root_mut(&mut self, root: StoredRoot) -> Option<&mut Arc> { + match root { + StoredRoot::Layer(i) => self.layers.get_mut(i), + StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art), + StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art), + StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art), + } + } + + /// Visit every stored object with its place: the layer tree with the opacity-mask art of its + /// objects, then the art of symbols, graph designs and pattern swatches (their definitions, + /// once each, never the copies instances and tiles draw). + pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) { + self.visit_stored_arcs(|n, place| f(n, place)); + } + + /// [`Self::visit_stored`] with each object's shared handle, which keeps its identity from one + /// look to the next while the object is unchanged (for caches such as thumbnails). + pub fn visit_stored_arcs<'a>(&'a self, mut f: impl FnMut(&'a Arc, StoredPlace)) { + for (root, r) in self.stored_roots() { + visit(root, StoredPlace { root: r, mask_of: None }, &mut f); + } + } + + /// Where object `id` is stored: the root, and the steps from it. + fn stored_path(&self, id: NodeId) -> Option<(StoredPlace, Vec)> { + if let Some(path) = self.index_path(id) { + let (first, rest) = path.split_first()?; + return Some((StoredPlace { root: StoredRoot::Layer(*first), mask_of: None }, rest.iter().map(|i| Step::Child(*i)).collect())); + } + // Not in the layer tree: in mask art (in the layers too) or in a definition's art. + for (root, r) in self.stored_roots() { + let (mut steps, mut mask_of) = (vec![], None); + if find(root, id, &mut steps, &mut mask_of) { + return Some((StoredPlace { root: r, mask_of }, steps)); + } + } + None + } + + /// Stored object `id` (see [`Self::visit_stored`]) with its place: one in the layer tree as + /// [`Self::node`] finds it, else the first in visiting order. + pub fn stored_node(&self, id: NodeId) -> Option<(&Arc, StoredPlace)> { + let (place, steps) = self.stored_path(id)?; + let root = self.stored_roots().find(|(_, r)| *r == place.root)?.0; + Some((at(root, &steps)?, place)) + } + + /// [`Self::stored_node`] to change; the nodes on the way are copied when shared. + pub fn stored_node_mut(&mut self, id: NodeId) -> Option<&mut Node> { + let (place, steps) = self.stored_path(id)?; + at_mut(self.stored_root_mut(place.root)?, &steps) + } + + /// Gives the objects outside the layer tree (in opacity-mask art and in the art of symbols, + /// graph designs and patterns) whose id is 0, past the id range, or already taken by an object + /// visited before them (the layer tree's own objects first) a new id, so every stored object + /// can be named by its id. Returns how many changed; the id counter then stands above them. + pub(crate) fn renumber_stored_duplicates(&mut self) -> usize { + let mut seen: HashSet = HashSet::new(); + for l in &self.layers { + l.walk(&mut |n| { + seen.insert(n.id); + }); + } + self.slices.iter().for_each(|s| { + seen.insert(s.id); + }); + // Per root, the visiting indices of the nodes that take a new id. + let mut fresh: Vec<(StoredRoot, HashSet)> = vec![]; + for (root, r) in self.stored_roots() { + let (mut i, mut here) = (0, HashSet::new()); + visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| { + if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) { + here.insert(i); + } + i += 1; + }); + if !here.is_empty() { + fresh.push((r, here)); + } + } + let total = fresh.iter().map(|(_, f)| f.len()).sum(); + if total == 0 { + return 0; + } + // No id left to give: the objects keep theirs rather than share one given out later. + if self.peek_next_id().saturating_add(total as u64) > MAX_NEXT_ID { + return 0; + } + let mut next = self.peek_next_id(); + for (r, f) in fresh { + if let Some(root) = self.stored_root_mut(r) { + renumber(root, &f, &mut 0, &mut next); + } + } + self.raise_next_id(next); + total + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{GraphDesign, OpacityMask, PatternDef, Symbol}; + use vectorcraft_geom::Rect; + + fn rect(id: u64) -> Node { + Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), crate::Appearance::default_art()) + } + + fn masked(id: u64, art: Node) -> Node { + rect(id).with_mask(Some(Box::new(OpacityMask::new(art, true)))) + } + + /// A document with object 10 in its layer, mask art 11 on it, and one object in a symbol, + /// a graph design and a pattern (ids `defs`). + fn doc(defs: [u64; 3]) -> Document { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, masked(10, rect(11))).unwrap(); + d.symbols.push(Symbol { name: "S".into(), art: Arc::new(rect(defs[0])), dynamic: false }); + d.graph_designs.push(GraphDesign { name: "G".into(), art: Arc::new(rect(defs[1])) }); + d.patterns.push(PatternDef::new("P", vec![Arc::new(rect(defs[2]))])); + d.raise_next_id(20); + d + } + + #[test] + fn stored_objects_are_found_in_every_art() { + let d = doc([12, 13, 14]); + let place = |id: u64| d.stored_node(NodeId(id)).map(|(n, p)| (n.id.0, p)); + assert!(place(10).unwrap().1.in_layers()); + assert_eq!(place(11).unwrap().1, StoredPlace { root: StoredRoot::Layer(0), mask_of: Some(NodeId(10)) }); + assert_eq!(place(12).unwrap().1.root, StoredRoot::Symbol(0)); + assert_eq!(place(13).unwrap().1.root, StoredRoot::GraphDesign(0)); + assert_eq!(place(14).unwrap().1.root, StoredRoot::Pattern { pattern: 0, art: 0 }); + assert!(d.node(NodeId(11)).is_none() && d.node(NodeId(12)).is_none(), "the layer lookup stays the layer tree's"); + assert!(d.stored_node(NodeId(99)).is_none()); + let mut seen = vec![]; + d.visit_stored(|n, _| seen.push(n.id.0)); + assert_eq!(seen, [d.layers[0].id.0, 10, 11, 12, 13, 14]); + } + + #[test] + fn stored_objects_change_by_id() { + let mut d = doc([12, 13, 14]); + let before = d.clone(); + d.stored_node_mut(NodeId(13)).unwrap().name = Some("changed".into()); + assert_eq!(d.graph_designs[0].art.name.as_deref(), Some("changed")); + assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art), "other art is not copied"); + assert_eq!(before.graph_designs[0].art.name, None, "the earlier document is unchanged"); + d.stored_node_mut(NodeId(11)).unwrap().name = Some("mask".into()); + assert_eq!(d.stored_node(NodeId(11)).unwrap().0.name.as_deref(), Some("mask")); + } + + #[test] + fn fix_next_id_gives_nested_duplicates_new_ids() { + // The symbol's object repeats the layer's object, the design's has no id, and the pattern's + // repeats the mask art's. + let mut d = doc([10, 0, 11]); + d.next_id = 1; + d.fix_next_id(); + let mut ids = vec![]; + d.visit_stored(|n, _| ids.push(n.id.0)); + let unique: HashSet = ids.iter().copied().collect(); + assert_eq!(unique.len(), ids.len(), "{ids:?}"); + assert!(!ids.contains(&0)); + assert_eq!(&ids[..3], &[d.layers[0].id.0, 10, 11], "the layer tree and the first mask art keep theirs"); + assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id()); + // Ids already unique are kept, and a second pass changes nothing. + let again = d.clone(); + assert_eq!(d.renumber_stored_duplicates(), 0); + assert_eq!(d, again); + } + + #[test] + fn renumbered_objects_on_path_keep_their_path_and_members() { + // A symbol's Objects on Path group whose path repeats the layer's object 10 and whose + // member has no id. + let mut d = doc([12, 13, 14]); + let (path, member) = (rect(10), rect(0)); + let rec = crate::objects_on_path::ObjectsOnPath::new(path.id, &[&member], crate::objects_on_path::CENTER, 0.0); + let mut g = Node::new(NodeId(15), crate::NodeKind::Group { children: vec![Arc::new(path), Arc::new(member)], clip: false }); + g.extras_mut().objects_on_path = Some(Box::new(rec)); + d.symbols[0].art = Arc::new(g); + d.fix_next_id(); + let art = &d.symbols[0].art; + let kids: Vec = art.children().unwrap().iter().map(|c| c.id).collect(); + assert!(kids.iter().all(|id| id.0 != 10 && id.0 != 0), "{kids:?}"); + let on_path = art.extras().objects_on_path.as_ref().unwrap(); + assert_eq!(on_path.path, kids[0]); + assert_eq!(on_path.members.iter().map(|m| m.id).collect::>(), [kids[1]]); + } +} diff --git a/crates/engine/src/cmd/linkfiles.rs b/crates/engine/src/cmd/linkfiles.rs index f2ce9d4d12..99295e5c79 100644 --- a/crates/engine/src/cmd/linkfiles.rs +++ b/crates/engine/src/cmd/linkfiles.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::NodeKind; use super::findfiles::{self, Limits, Visitor}; -use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, checked_ids_param, cmd}; +use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, cmd, ids_param}; /// The most linked files one search looks for. const MAX_LINKS: usize = 1_000; @@ -143,8 +143,14 @@ fn find(s: &mut Session, p: &Value) -> Result { let ids = match p.get("ids") { None | Some(Value::Null) => None, Some(_) => { - let ids = checked_ids_param(s, p, "ids", C)?; - let linkable = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_))); + // Images and placed documents in opacity-mask art and in the art of symbols, graph + // designs and patterns are named by their ids too (`links.list`). + let ids = ids_param(p, "ids", C)?.unwrap_or_default(); + let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind); + if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) { + return Err(bad(C, format!("no such object id {value}"))); + } + let linkable = |id: &NodeId| matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_))); if let Some(id) = ids.iter().find(|id| !linkable(id)) { return Err(bad(C, format!("object {} is not an image or a linked file", id.0))); } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index d79320c304..3bfd4a1217 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -30,6 +30,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::links::{Align, Preserve, hash_bytes}; use vectorcraft_doc::{ Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions, + StoredPlace, StoredRoot, }; use vectorcraft_geom::{Affine, PathData, Rect, shapes}; @@ -43,7 +44,7 @@ pub fn specs() -> Vec { "Check Links", [], None, - "{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots", + "{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, check ), @@ -52,7 +53,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids]}", has_doc, update ), @@ -70,7 +71,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots)}", has_doc, relink ), @@ -79,7 +80,7 @@ pub fn specs() -> Vec { "Links", [], None, - "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", + "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, list ), @@ -88,7 +89,7 @@ pub fn specs() -> Vec { "Go To Link", [], None, - "{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}", + "{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)", has_doc, go_to ), @@ -156,7 +157,8 @@ impl Status { struct Group { link: LinkInfo, key: String, - /// The objects in the layers (images in symbols and patterns share the content, not an id). + /// The stored objects showing it: in the layers, in opacity-mask art and in the art of symbols, + /// graph designs and patterns ([`Document::visit_stored`]), each once. ids: Vec, /// Placed documents: what they show. document: Option, @@ -175,13 +177,16 @@ fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option)> { } } -/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]). +/// Every linked file of `d` with the ids of the objects showing it, wherever they are stored (for +/// [`crate::link_watch`]). pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { groups(d, None).into_iter().filter(|g| !g.ids.is_empty()).map(|g| (g.link.path, ids_json(&g.ids))).collect() } -/// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when -/// given), then, without `ids`, the ones only symbols and patterns show. +/// The linked images and placed documents of `d` by file and content, wherever they are stored +/// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object +/// visited before it has (art being edited on a layer and its definition) counts once, by its +/// first place; without `ids` its content is still grouped. fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { let mut out: Vec = vec![]; let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new(); @@ -196,24 +201,48 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { g.ids.push(id); } }; - d.walk(|n| { - if let Some((l, key, document)) = linked(n) - && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) - { + let mut seen = std::collections::HashSet::new(); + d.visit_stored(|n, _| { + let Some((l, key, document)) = linked(n) else { return }; + // Id 0 names no object. + let first = n.id.0 != 0 && seen.insert(n.id); + if first && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) { add(l, key, document, Some(n.id)); + } else if ids.is_none() { + add(l, key, document, None); } }); - if ids.is_none() { - d.visit_images(|_, im| { - if let Some(l) = &im.link { - add(l, &im.key, None, None); - } - }); - d.visit_placed(|_, p| add(&p.link, &p.key, Some((p.bounding, p.page_box)), None)); - } out } +/// Stored object `id` of `d` ([`Document::stored_node`]). +fn stored(d: &Document, id: NodeId) -> Option<&Node> { + d.stored_node(id).map(|(n, _)| &**n) +} + +/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none). +fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet { + ids.iter().copied().filter(|id| d.node(*id).is_none()).collect() +} + +/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree +/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`. +fn owner_json(d: &Document, place: StoredPlace) -> Option { + if place.in_layers() { + return None; + } + let mut owner = match place.root { + StoredRoot::Layer(_) => json!({ "kind": "layers" }), + StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }), + StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }), + StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }), + }; + if let Some(m) = place.mask_of { + owner["maskOf"] = json!(m.0); + } + Some(owner) +} + /// A linked file where it was found. struct Found { path: String, @@ -455,8 +484,8 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a } /// The linked files of the open document `st` that `links.findFiles` looks for, each with the -/// objects in the layers that show it: the files of objects `ids` whatever their status, else the -/// files that can't be found. +/// stored objects that show it: the files of objects `ids` whatever their status, else the files +/// that can't be found. pub(crate) fn files_to_find(st: &crate::DocState, ids: Option<&[NodeId]>) -> Vec<(LinkInfo, Vec)> { groups(&st.doc, ids) .into_iter() @@ -587,7 +616,7 @@ fn clip_shape((frame, room): Clip) -> PathData { } /// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and -/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for. +/// opacity masks, where [`Document::node`] does not find them) that `pick` holds for. struct Nested<'a> { pick: &'a dyn Fn(&Node) -> bool, /// The object an object becomes, and the clip it takes ([`placed_xf`]). @@ -703,10 +732,10 @@ impl Nested<'_> { } } -/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its -/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also` -/// (a file's path and the content shown), so do the placed documents outside the layer tree that -/// show that content. +/// Placed documents `ids` (in the layers or outside them) show `src`, read from the file `link` +/// points at, each placed as its Placement Options say (`force`: as that Preserve choice says, +/// whatever they say); with `also` (a file's path and the content shown), so do the placed +/// documents outside the layer tree that show that content. fn install_document( d: &mut Document, ids: &[NodeId], @@ -721,8 +750,10 @@ fn install_document( let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement }; placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o) }; - if let Some(also) = also { - let pick = |n: &Node| shows(n, also, true); + let nested = nested_ids(d, ids); + if also.is_some() || !nested.is_empty() { + let pick = + |n: &Node| matches!(n.kind, NodeKind::PlacedDocument(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, true))); let mut make = |n: &Node| { let mut n = n.clone(); let mut clip = None; @@ -843,22 +874,33 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } -/// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement -/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's -/// path and the content shown), so do the images outside the layer tree that show that content. +/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each +/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); +/// with `also` (a file's path and the content shown), so do the images outside the layer tree that +/// show that content. fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { let new_pt = super::place::pt_per_px(img.ppi); let mut clips = vec![]; - if let Some(also) = also { - // Every image picked shows content `also.1`, so one resolution serves them all. - let old_pt = file_pt(d, also.1); - let pick = |n: &Node| shows(n, also, false); + let nested = nested_ids(d, ids); + if also.is_some() || !nested.is_empty() { + let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false))); + // The resolution of each content the images picked show, looked up once each. + let mut old_pts: BTreeMap = BTreeMap::new(); + d.visit_stored(|n, _| { + if let NodeKind::Image(im) = &n.kind + && pick(n) + && !old_pts.contains_key(&im.key) + { + old_pts.insert(im.key.clone(), file_pt(d, &im.key)); + } + }); let mut make = |n: &Node| { let mut n = n.clone(); let mut clip = None; if let NodeKind::Image(im) = &mut n.kind { let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); + let old_pt = old_pts.get(&im.key).copied().unwrap_or_else(|| super::place::pt_per_px(None)); let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); clip = c; @@ -1039,7 +1081,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps } } // The objects in symbols, graph designs, patterns and opacity masks that show the same file and - // content, which have no ids here, whatever else their links hold. + // content, whatever else their links hold, those whose id an earlier object has included. if !moved.is_empty() { let mut by_path: BTreeMap> = BTreeMap::new(); for (path, key, document, new) in moved { @@ -1074,13 +1116,25 @@ fn link_mut(n: &mut Node) -> Option<&mut LinkInfo> { } } -/// Linked image objects (or placed documents) `ids` link to `link`. +/// Linked image objects (or placed documents) `ids`, in the layers or outside them, link to `link`. fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) { - for id in ids { + let nested = nested_ids(d, ids); + for id in ids.iter().filter(|id| !nested.contains(id)) { if let Some(l) = d.node_mut(*id).and_then(link_mut) { *l = link.clone(); } } + if !nested.is_empty() { + let pick = |n: &Node| nested.contains(&n.id) && linked(n).is_some(); + let mut make = |n: &Node| { + let mut out = n.clone(); + if let Some(l) = link_mut(&mut out) { + *l = link.clone(); + } + (out, None) + }; + Nested { pick: &pick, make: &mut make, next: 0 }.run(d); + } } /// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open @@ -1309,7 +1363,7 @@ fn update(s: &mut Session, p: &Value) -> Result { /// Update Links in the active document of `s` for objects `ids` (default: the linked files that /// changed or show their preview), or with `path`, for the placed documents of the file at `path` /// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that -/// show the same content are read again too, and have no ids to report. +/// show the same content are read again too. fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) -> Result { let st = s.doc()?; let (mut reads, mut missing) = (vec![], vec![]); @@ -1341,7 +1395,7 @@ enum Scope { Each, /// The objects given or selected. Selected, - /// Every object in the layers linked to the same file as one given or selected. + /// Every stored object linked to the same file as one given or selected. All, /// The objects given or selected, then every other missing link whose file name is in the new /// file's folder. @@ -1425,7 +1479,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { }; // An image or a placed document, with its link. let image = |id: &NodeId| { - st.doc.node(*id).and_then(|n| match &n.kind { + stored(&st.doc, *id).and_then(|n| match &n.kind { NodeKind::Image(im) => Some(im.link.as_ref()), NodeKind::PlacedDocument(p) => Some(Some(&p.link)), _ => None, @@ -1450,22 +1504,23 @@ fn relink(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the images to relink, or pass ids")); } - // All Instances: the other objects in the layers linked to the same files. + // All Instances: the other stored objects linked to the same files, each once. if scope == Scope::All { let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect(); - let given: BTreeSet = ids.iter().copied().collect(); + let mut given: BTreeSet = ids.iter().copied().collect(); let mut more = vec![]; - st.doc.walk(|n| { + st.doc.visit_stored(|n, _| { if let Some((l, _, _)) = linked(n) && paths.contains(l.path.as_str()) - && !given.contains(&n.id) + && n.id.0 != 0 + && given.insert(n.id) { more.push(n.id); } }); ids.extend(more); } - if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) { + if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) { return Err(bad(C, "copy takes images only: relink placed documents where their files are")); } // (ids, the file) per file to read. @@ -1501,7 +1556,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { let mut images = vec![]; let mut documents: Vec<((u32, bool, PageBox), Vec)> = vec![]; for id in ids { - match st.doc.node(id).map(|n| &n.kind) { + match stored(&st.doc, id).map(|n| &n.kind) { Some(NodeKind::PlacedDocument(pl)) => { let k = (pl.page(), pl.bounding, pl.page_box); match documents.iter_mut().find(|(e, _)| *e == k) { @@ -1643,9 +1698,9 @@ fn copy_into_folder(_: &str, _: &[u8], _: &Path) -> Result<(String, bool)> { // ---------- the Links panel ---------- -/// Image object `id` of `d`. +/// Image object `id` of `d`, wherever it is stored. fn image_of(d: &Document, id: NodeId) -> Option<&ImageObject> { - match &d.node(id)?.kind { + match &stored(d, id)?.kind { NodeKind::Image(im) => Some(im), _ => None, } @@ -1663,7 +1718,7 @@ fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { .ok_or_else(|| bad(cmd, "select an image, or pass id"))?; match image_of(&st.doc, id) { Some(_) => Ok(id), - None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)), + None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)), None => Err(bad(cmd, format!("object {} is not an image", id.0))), } } @@ -1677,9 +1732,9 @@ fn placement_mut(n: &mut Node) -> Option<&mut PlacementOptions> { } } -/// The Placement Options of image or placed document `id` of `d`. +/// The Placement Options of image or placed document `id` of `d`, wherever it is stored. fn placement_of(d: &Document, id: NodeId) -> Option { - match &d.node(id)?.kind { + match &stored(d, id)?.kind { NodeKind::Image(im) => Some(im.placement), NodeKind::PlacedDocument(p) => Some(p.placement), _ => None, @@ -1692,12 +1747,12 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?; match placement_of(&st.doc, id) { Some(_) => Ok(id), - None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)), + None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)), None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))), } } -/// Per linked image in the layers of `st`: its file's status, where it was found when away from +/// Per linked image or placed document of `st`, wherever it is stored: its file's status, where it was found when away from /// its path, and whether the image shows its preview (each file probed once). pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { let mut out = BTreeMap::new(); @@ -1740,17 +1795,20 @@ fn list(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("show `{show}`: all, missing, modified or embedded"))); } let statuses = statuses(st); - let mut objects = vec![]; - st.doc.walk(|n| { - if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) { - objects.push(n); + // The layer tree's objects, top first as the Layers panel lists them, then the others in the + // order they are stored (opacity-mask art, symbols, graph designs, patterns), each once. + let (mut objects, mut nested) = (vec![], vec![]); + let mut seen = std::collections::HashSet::new(); + st.doc.visit_stored(|n, place| { + if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) { + if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) } } }); - // Top first, as the Layers panel lists them. objects.reverse(); + objects.extend(nested); let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); let mut rows = vec![]; - for n in objects { + for (n, place) in objects { let (status, found, preview) = match statuses.get(&n.id) { Some((s, f, p)) => (s.as_str(), f.as_deref(), *p), None => ("embedded", None, false), @@ -1793,6 +1851,9 @@ fn list(s: &mut Session, p: &Value) -> Result { if preview { row["preview"] = json!(true); } + if let Some(owner) = owner_json(&st.doc, place) { + row["owner"] = owner; + } rows.push(row); } let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_lowercase(); @@ -1810,15 +1871,21 @@ fn list(s: &mut Session, p: &Value) -> Result { fn go_to(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let id = linked_param(st, p, "links.goTo")?; + // An object in mask art or a definition has no place of its own on the canvas: the selection + // is cleared, and the reply names what holds it. + if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) { + s.select(|_, sel| sel.set([]))?; + return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner })); + } let b = st.doc.node(id).and_then(Node::geometric_bounds).unwrap_or_default(); s.select(|_, sel| sel.set([id]))?; - Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1] })) + Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1], "onCanvas": true })) } fn embed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.embed"; let st = s.doc()?; - let kind = |id: &NodeId| st.doc.node(*id).map(|n| &n.kind); + let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind); let linked = |id: &NodeId| match kind(id) { Some(NodeKind::Image(im)) => im.link.is_some(), Some(NodeKind::PlacedDocument(_)) => true, @@ -1864,7 +1931,7 @@ fn embed(s: &mut Session, p: &Value) -> Result { install(d, &ids, read, Some(Preserve::Bounds), None)?; } for id in &done { - if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) { + if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) { im.link = None; } } @@ -1892,7 +1959,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; let st = s.doc()?; let id = image_param(st, p, C)?; - let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?; + let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?; let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; if im.link.is_some() { return Err(bad(C, format!("image {} is linked already", id.0))); @@ -1978,7 +2045,7 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) { /// Link Info of placed document `id`. fn placed_info(st: &crate::DocState, id: NodeId) -> Result { - let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?; + let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?; let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) }; let size = n.geometric_bounds().unwrap_or_default(); let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0)); @@ -2058,7 +2125,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { }; s.edit("Placement Options", |d, _| { for id in &ids { - if let Some(o) = d.node_mut(*id).and_then(placement_mut) { + if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) { set(o); } } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 5d56a2b646..6acad1e83b 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -885,7 +885,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { (None, [id]) => *id, _ => return Err(bad(C, "select one image or pass id")), }; - let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?; + // An image in opacity-mask art or a definition's art is found by its id too (`links.list`). + let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; // Effective resolution: 72 pt per inch over the points one pixel spans along each axis. let [a, b, c, d, ..] = im.xf.as_coeffs(); diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 15a39f06e5..0a0f08d3c1 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -272,6 +272,8 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() { def.name = new.to_string(); refs(Arc::make_mut(&mut def.art), &mut rename); + // The art takes ids of `dst`: those of `src` may name objects of `dst` already. + def.art = Arc::new(dst.reid(&def.art)); dst.symbols.push(def); } } @@ -280,6 +282,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { def.name = new.to_string(); for a in &mut def.art { refs(Arc::make_mut(a), &mut rename); + *a = Arc::new(dst.reid(a)); } dst.patterns.push(def); } diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 9f58e4851d..8e4afaa295 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -378,8 +378,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec) { /// Placed document `id` of `d` replaced by an editable copy of its art, as placing its file /// without Link gives (its resources joining `d`, renamed where `d` uses a name for something /// else), keeping the object's id, place, name and transparency: Break Link and Object › Expand. +/// A placed document in opacity-mask art or in the art of a symbol, graph design or pattern is +/// replaced where it is stored. pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> { - let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let n = d.stored_node(id).map(|(n, _)| Node::clone(n)).ok_or(EngineError::NoNode(id))?; let NodeKind::PlacedDocument(p) = &n.kind else { return Err(bad(cmd, format!("object {} is not a placed document", id.0))) }; let blob = d.images.get(&p.key).ok_or_else(|| bad(cmd, format!("object {} has lost its file's contents: relink it", id.0)))?; let bytes = vectorcraft_doc::placed_document::full_bytes(p, blob) @@ -395,6 +397,10 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> { let art = super::transformed(Node::new(d.alloc_id(), NodeKind::Group { children, clip: a.clip.is_some() }), m); let mut out = n.clone(); out.kind = art.kind; + if d.node(id).is_none() { + *d.stored_node_mut(id).ok_or(EngineError::NoNode(id))? = out; + return Ok(()); + } let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; d.remove(id)?; d.insert(par, index, out)?; diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index a3c7a72aee..1f82795399 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind}; +use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind, StoredRoot}; use vectorcraft_geom::Rect; use crate::*; @@ -446,8 +446,8 @@ fn links_outside_the_layers_find_their_files_after_the_folder_moves() { } /// With Update Links: Automatically, a file in a symbol and in the layers that changed and moved -/// with the document is read again for the layers' image and for the symbol's, and both links take -/// its new path, size and hash. +/// with the document is read again for the layers' image and for the symbol's, both are listed by +/// their ids, and both links take its new path, size and hash. #[test] fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() { let a = Folder::new("nested-modified-a"); @@ -458,13 +458,14 @@ fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() { s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap(); let id = place(&mut s, &pic); s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0)); let id = place(&mut s, &pic); save(&mut s, &a.file("poster.vectorcraft")); write(&pic, &png(30, 30, BLUE)); std::fs::remove_dir_all(&b.0).unwrap(); std::fs::rename(&a.0, &b.0).unwrap(); let r = open(&mut s, &b.file("poster.vectorcraft")); - assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0])), "{r}"); + assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0, in_symbol.0])), "{r}"); let moved = PathBuf::from(b.file("art/photo.png")); let blue = png(30, 30, BLUE); let mut images = vec![]; @@ -521,7 +522,8 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() { /// Update Links reads a changed file again for the images inside symbols, patterns and opacity /// masks too: those showing the same content as an image in the layers, and those no object in the -/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step. +/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step, +/// and the reply lists each by its id. #[test] fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { let dir = Folder::new("nested-update"); @@ -533,11 +535,13 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { let id = place(&mut s, &photo); s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0)); let id = place(&mut s, &photo); // logo.png only in a pattern and in an opacity mask. let p = place(&mut s, &logo); s.execute("object.pattern.make", &json!({"ids": [p.0], "edit": false})).unwrap(); s.execute("edit.clear", &json!({"ids": [p.0]})).unwrap(); + let p = stored_image_in(&s, StoredRoot::Pattern { pattern: 0, art: 0 }); let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); let mask = place(&mut s, &logo); s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); @@ -546,7 +550,8 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { write(&photo, &blue); write(&logo, &green); let u = s.execute("links.update", &json!({})).unwrap(); - assert_eq!(u, json!({"updated": [id.0], "missing": []})); + // By file: photo.png in the layers and the symbol, then logo.png in the mask and the pattern. + assert_eq!(u, json!({"updated": [id.0, in_symbol.0, mask.0, p.0], "missing": []})); // (name, size, hash, pixel size) of each image, which shows its file's pixels. let images = |s: &Session| { let d = &s.doc().unwrap().doc; @@ -576,6 +581,193 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s)); } +/// The files only art outside the layers shows: one in a symbol, a graph design, a pattern and an +/// opacity mask each, no object in the layers linked to any of them. +const NESTED: [&str; 4] = ["symbol.png", "design.png", "pattern.png", "mask.png"]; + +/// A document whose only links are [`NESTED`]'s files in `dir`. +fn nested_links(dir: &Folder) -> Session { + for (i, name) in (0u8..).zip(NESTED) { + write(&dir.file(name), &png(20, 10, [20 + 50 * i, 90, 160])); + } + let mut s = session(); + let id = place(&mut s, &dir.file("symbol.png")); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + s.execute("edit.clear", &json!({"ids": [s.doc().unwrap().selection.objects[0].0]})).unwrap(); + let id = place(&mut s, &dir.file("design.png")); + s.execute("graph.design", &json!({"new": "Bar"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let id = place(&mut s, &dir.file("pattern.png")); + s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); + let mask = place(&mut s, &dir.file("mask.png")); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s +} + +/// The id of the `links.list` row of file `name`. +fn row_id(s: &mut Session, name: &str) -> u64 { + let list = s.execute("links.list", &json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name).unwrap_or_else(|| panic!("{name} in {list}")); + row["id"].as_u64().unwrap() +} + +/// The link of stored object `id`. +fn stored_link(s: &Session, id: u64) -> Option { + match &s.doc().unwrap().doc.stored_node(NodeId(id)).unwrap().0.kind { + NodeKind::Image(im) => im.link.clone(), + k => panic!("not an image: {k:?}"), + } +} + +/// The id of the first image stored in the art of `root`. +fn stored_image_in(s: &Session, root: StoredRoot) -> NodeId { + let mut found = None; + s.doc().unwrap().doc.visit_stored(|n, place| { + if found.is_none() && place.root == root && matches!(n.kind, NodeKind::Image(_)) { + found = Some(n.id); + } + }); + found.unwrap_or_else(|| panic!("no image in {root:?}")) +} + +/// Images in symbols, graph designs, patterns and opacity masks are listed and checked with ids of +/// their own, one row each with what holds it, and the missing filter counts them. +#[test] +fn links_outside_the_layers_are_listed_and_checked_with_ids() { + let dir = Folder::new("nested-ids"); + let mut s = nested_links(&dir); + let list = s.execute("links.list", &json!({})).unwrap(); + let rows = list["links"].as_array().unwrap(); + let owners: Vec<(&str, &str)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), r["owner"]["kind"].as_str().unwrap_or("-"))).collect(); + assert_eq!(owners, [("mask.png", "layers"), ("symbol.png", "symbol"), ("design.png", "graphDesign"), ("pattern.png", "pattern")], "{list}"); + assert_eq!(rows[1]["owner"]["name"], "Mark"); + let masked = s.doc().unwrap().doc.layers[0].children().unwrap().iter().find(|n| n.extras().mask.is_some()).unwrap().id; + assert_eq!(rows[0]["owner"]["maskOf"], json!(masked.0)); + let ids: std::collections::BTreeSet = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 4, "{list}"); + assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}"); + let check = s.execute("links.check", &json!({})).unwrap(); + let checked: Vec<(&str, &Value)> = check["links"].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap(), &l["ids"])).collect(); + assert_eq!(checked.len(), 4, "{check}"); + for (name, ids) in checked { + assert_eq!(*ids, json!([row_id(&mut s, name)]), "{check}"); + } + std::fs::remove_file(dir.file("design.png")).unwrap(); + let check = s.execute("links.check", &json!({})).unwrap(); + assert_eq!((check["missing"].as_u64(), check["modified"].as_u64()), (Some(1), Some(0)), "{check}"); + let design = row_id(&mut s, "design.png"); + let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap(); + assert_eq!((missing["missing"].as_u64(), &missing["links"][0]["id"]), (Some(1), &json!(design)), "{missing}"); + let one = s.execute("links.check", &json!({"ids": [design]})).unwrap(); + assert_eq!(one["links"][0]["status"], "missing", "{one}"); +} + +/// Every links command takes the id of an image outside the layers and acts on that object: Link +/// Info, Go To (which clears the selection and names the symbol), Placement Options, Relink, Update and +/// Embed. +#[test] +fn links_commands_act_on_images_outside_the_layers_by_id() { + let dir = Folder::new("nested-act"); + let mut s = nested_links(&dir); + let symbol = row_id(&mut s, "symbol.png"); + let info = s.execute("links.info", &json!({"id": symbol})).unwrap(); + assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("symbol.png"), Some("ok"), Some(symbol)), "{info}"); + let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + let go = s.execute("links.goTo", &json!({"id": symbol})).unwrap(); + assert_eq!( + (go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()), + (json!(false), json!("symbol"), json!("Mark")), + "{go}" + ); + assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected"); + s.execute("links.placementOptions", &json!({"ids": [symbol], "preserve": "fit"})).unwrap(); + let placement = s.execute("links.placementOptions", &json!({"ids": [symbol]})).unwrap(); + assert_eq!(placement["placement"]["preserve"], "fit"); + // Relink: the symbol's image shows the new file. + let other = dir.file("other.png"); + write(&other, &png(40, 20, BLUE)); + let r = s.execute("links.relink", &json!({"ids": [symbol], "path": other})).unwrap(); + assert_eq!(r["relinked"], json!([symbol]), "{r}"); + assert_eq!(stored_link(&s, symbol).unwrap().path, other); + // Update: a changed pattern file is read again for the pattern's image. + let pattern = row_id(&mut s, "pattern.png"); + let changed = png(30, 30, RED); + write(&dir.file("pattern.png"), &changed); + let r = s.execute("links.update", &json!({"ids": [pattern]})).unwrap(); + assert_eq!(r["updated"], json!([pattern]), "{r}"); + assert_eq!(stored_link(&s, pattern).unwrap().size, Some(changed.len() as u64)); + // Embed: the design's image keeps its pixels and no longer links. + let design = row_id(&mut s, "design.png"); + let r = s.execute("links.embed", &json!({"ids": [design]})).unwrap(); + assert_eq!(r["embedded"], json!([design]), "{r}"); + assert!(stored_link(&s, design).is_none()); + let row = s.execute("links.list", &json!({"show": "embedded"})).unwrap(); + assert_eq!(row["links"][0]["id"], json!(design), "{row}"); + // Relink All Instances takes the other stored objects linked to the same file. + let mask = row_id(&mut s, "mask.png"); + let r = s.execute("links.relink", &json!({"ids": [symbol], "path": dir.file("mask.png"), "scope": "all"})).unwrap(); + assert_eq!(r["relinked"], json!([symbol]), "{r}"); + let r = s.execute("links.relink", &json!({"ids": [mask], "path": other, "scope": "all"})).unwrap(); + let mut relinked: Vec = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + relinked.sort(); + let mut both = vec![symbol, mask]; + both.sort(); + assert_eq!(relinked, both, "{r}"); +} + +/// Opening a document reports missing and modified files that only art outside the layers shows, +/// by their objects' ids, and those ids stay the same after the document is saved and opened again. +#[test] +fn open_reports_links_outside_the_layers_by_id() { + let dir = Folder::new("nested-open"); + let mut s = nested_links(&dir); + let path = dir.file("poster.vectorcraft"); + save(&mut s, &path); + let ids: Vec = NESTED.iter().map(|name| row_id(&mut s, name)).collect(); + std::fs::remove_file(dir.file("symbol.png")).unwrap(); + write(&dir.file("pattern.png"), &png(30, 30, RED)); + let r = open(&mut s, &path); + let names = |k: &str| r[k].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap().to_string(), l["ids"].clone())).collect::>(); + assert_eq!(names("missingLinks"), [("symbol.png".to_string(), json!([ids[0]]))], "{r}"); + assert_eq!(names("modifiedLinks"), [("pattern.png".to_string(), json!([ids[2]]))], "{r}"); + let again: Vec = NESTED.iter().map(|name| row_id(&mut s, name)).collect(); + assert_eq!(again, ids, "the ids are saved"); +} + +/// A document whose symbol and mask art repeat the ids of objects in the layers (or have none) +/// opens with ids of their own there, the layer tree's kept; the links commands then tell them apart. +#[test] +fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() { + let dir = Folder::new("nested-repeat"); + let mut s = nested_links(&dir); + let layer_image = place(&mut s, &dir.file("symbol.png")); + let path = dir.file("poster.vectorcraft"); + save(&mut s, &path); + // The symbol's image takes the id of the image in the layers, the mask's image none. + let mut saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + saved["document"]["symbols"][0]["art"]["id"] = json!(layer_image.0); + let layer = &mut saved["document"]["layers"][0]["kind"]["children"]; + let masked = layer.as_array_mut().unwrap().iter_mut().find(|n| n.get("mask").is_some() || n["extras"].get("mask").is_some()).unwrap(); + let mask = if masked.get("mask").is_some() { &mut masked["mask"] } else { &mut masked["extras"]["mask"] }; + mask["art"]["id"] = json!(0); + std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); + open(&mut s, &path); + let list = s.execute("links.list", &json!({})).unwrap(); + let ids: Vec = list["links"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect(); + let unique: std::collections::BTreeSet = ids.iter().copied().collect(); + assert_eq!((ids.len(), unique.len()), (5, 5), "{list}"); + assert!(!ids.contains(&0), "{list}"); + assert_eq!(list["links"][0]["id"], json!(layer_image.0), "the layer tree keeps its ids: {list}"); + let symbol = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").unwrap()["id"].as_u64().unwrap(); + s.execute("links.embed", &json!({"ids": [symbol]})).unwrap(); + assert!(stored_link(&s, symbol).is_none()); + assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked"); +} + #[test] fn a_missing_link_renders_its_preview_and_relinks() { let dir = Folder::new("missing"); diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index f029eccd3d..a9a3a17ec7 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -213,7 +213,7 @@ fn go_to_selects_the_image() { run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); assert_ne!(s.doc().unwrap().selection.objects, vec![id]); let r = run(&mut s, "links.goTo", json!({"id": id.0})); - assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0]})); + assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0], "onCanvas": true})); assert_eq!(s.doc().unwrap().selection.objects, vec![id]); let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[1].id; assert!(s.execute("links.goTo", &json!({"id": rect.0})).is_err(), "not an image"); diff --git a/crates/engine/src/tests/linkwatch.rs b/crates/engine/src/tests/linkwatch.rs index 7fc8f0a4ba..0a5b9d7dbe 100644 --- a/crates/engine/src/tests/linkwatch.rs +++ b/crates/engine/src/tests/linkwatch.rs @@ -47,6 +47,30 @@ fn update_changed_reads_changed_files_again_once() { assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 1); } +/// A file only a symbol's art shows is watched too, and read again by the id of the symbol's image. +#[test] +fn update_changed_reads_a_file_only_a_symbol_shows() { + let dir = Folder::new("watch-symbol"); + let path = dir.file("art.png"); + std::fs::write(&path, png(40, 40, RED)).unwrap(); + let mut s = session(); + let id = place(&mut s, &path); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let instance = s.doc().unwrap().selection.objects[0]; + s.execute("edit.clear", &json!({"ids": [instance.0]})).unwrap(); + let mut in_symbol = None; + s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)) { + in_symbol = Some(n.id.0); + } + }); + let in_symbol = in_symbol.expect("the symbol's image"); + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([])); + save(&path, &png(40, 40, BLUE)); + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([in_symbol])); + assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0); +} + #[test] fn a_background_look_follows_update_links() { for (mode, key) in [("automatically", "updated"), ("askWhenModified", "ask"), ("manually", "modified")] { diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index a0a8ededa0..455471dbb1 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -662,6 +662,33 @@ fn placed_art_brings_its_symbols_and_swatches_renaming_on_conflict() { assert!(linked, "still linked to the swatch it brought"); } +/// The symbol and pattern art placed art brings takes ids of the document's own: the file's ids +/// already name other objects there, and the Links panel names linked art in symbols by its id. +#[test] +fn placed_art_brings_its_symbols_and_patterns_with_ids_of_the_documents_own() { + let mut src = session(); + src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star"})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + // The document's objects take the same ids the file's do. + let mut s = session(); + for x in [0, 20, 40, 60] { + s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap(); + } + s.execute("symbol.new", &json!({"name": "Box"})).unwrap(); + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let doc = &s.doc().unwrap().doc; + assert!(doc.symbols.iter().any(|x| x.name == "Star") && doc.pattern("Dots").is_some()); + let mut ids = vec![]; + doc.visit_stored(|n, _| ids.push(n.id.0)); + let unique: std::collections::BTreeSet = ids.iter().copied().collect(); + assert_eq!(unique.len(), ids.len(), "{ids:?}"); +} + #[test] fn placed_art_brings_its_brushes_renaming_on_conflict() { // The file: a path with its own brush, and one with a brush the defaults hold. diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs index 0b367a7ba0..d50d650215 100644 --- a/crates/ui-egui/src/addons/select/link_status.rs +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -52,12 +52,19 @@ pub struct Present { pub has: [bool; 4], } -/// The statuses the `links.list` result `list` holds, in [`STATUSES`] order. +/// The statuses the rows of the `links.list` result `list` that can be selected hold, in +/// [`STATUSES`] order. pub(crate) fn statuses_in(list: &Value) -> [bool; 4] { - let rows = list["links"].as_array().map_or(&[][..], Vec::as_slice); + let rows = canvas_rows(list); STATUSES.map(|(status, ..)| rows.iter().any(|r| command_status(r) == status)) } +/// The rows of the `links.list` result `list` of objects in the layer tree, which can be +/// selected (a row with an `owner` is in a symbol, graph design, pattern or opacity mask). +fn canvas_rows(list: &Value) -> Vec { + list["links"].as_array().into_iter().flatten().filter(|r| r["owner"].is_null()).cloned().collect() +} + /// The status of a `links.list` row as the command names it (`ok` is `linked`). fn command_status(row: &Value) -> &str { match row["status"].as_str().unwrap_or_default() { @@ -154,11 +161,11 @@ pub(crate) fn message(statuses: &[&str], count: u64, reasons: &[&str]) -> String crate::i18n::msg_n(reasons.len() as u64, one, other, &[("selected", &selected)]) } -/// The dialog's fields to start with: every image and placed document (`__rows`, as `links.list` -/// lists them, read once), those selected chosen, All shown, Zoom to Selection on. +/// The dialog's fields to start with: every image and placed document in the layer tree (`__rows`, +/// as `links.list` lists them, read once), those selected chosen, All shown, Zoom to Selection on. pub(crate) fn fields(app: &mut VectorcraftApp) -> Value { let list = app.session.execute("links.list", &json!({})).unwrap_or_default(); - let rows: Vec = list["links"].as_array().cloned().unwrap_or_default(); + let rows = canvas_rows(&list); let selected: Vec = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default(); let chosen: Vec = rows.iter().filter_map(|r| r["id"].as_u64()).filter(|id| selected.contains(id)).collect(); json!({ "__rows": rows, "ids": chosen, "show": "all", "zoom": true }) diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs index 8ad61f6e5a..c0515e048b 100644 --- a/crates/ui-egui/src/addons/select/link_status/tests.rs +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -138,6 +138,27 @@ fn menu_items_are_on_for_the_statuses_present_and_shift_adds() { assert!(on("Select Embedded")); } +/// A missing link kept only in a symbol's art can't be selected: Select Missing stays off and +/// the dialog does not list it. +#[test] +fn links_inside_a_symbol_are_left_out_of_selecting_by_status() { + let dir = Folder::new("symbol"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let path = dir.file("inside.png", &png(30, 20)); + let id = app.run("file.place", json!({"path": path, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("symbol.new", json!({"name": "Mark", "ids": [id]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + std::fs::remove_file(&path).unwrap(); + let list = app.run("links.list", json!({})).unwrap(); + assert_eq!(list["missing"], 1, "{list}"); + refresh(&mut app, 0.0); + let entries = menus::menu_entries(&app); + let missing = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == "Select Missing").unwrap(); + assert!(!missing.enabled); + assert_eq!(super::fields(&mut app)["__rows"], json!([])); +} + #[test] fn the_links_panel_menu_lists_the_select_items() { let dir = Folder::new("flyout"); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 33df72c253..3b6cfa4bc6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5715,6 +5715,7 @@ digits Malayalam Malaiàlam @msg no library `{id}` no hi ha la biblioteca `{id}` @msg no library `{key}` (see {list}) no hi ha la biblioteca `{key}` (vegeu {list}) @msg No linked files to look for No hi ha fitxers enllaçats per buscar +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas L’enllaç és dins d’un símbol, un disseny de gràfic, un motiu o una màscara d’opacitat i no té lloc al llenç @msg no Live Paint edge near that point no hi ha cap aresta de pintura interactiva a prop d’aquell punt @msg no Live Paint face at that point no hi ha cap cara de pintura interactiva en aquell punt @msg no native format no hi ha format natiu diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ff48f1ecfc..e0cb12f675 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5400,6 +5400,7 @@ imageTrace Outline Obrys @msg every numbered name for it is taken in the Fonts folder ve složce Fonts jsou obsazena všechna číslovaná jména pro tento soubor @msg every numbered name for {name} is taken in the document's folder ve složce dokumentu jsou obsazena všechna číslovaná jména pro {name} @msg No linked files to look for Žádné propojené soubory k vyhledání +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Propojení je uvnitř symbolu, návrhu grafu, vzorku nebo masky krytí a nemá na plátně žádné místo @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` je odkaz na krok {r}, který vyhodnocují jen `run` a `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` musí být pole ID objektů, ne {v} @msg `colors` must be an array of colors, not {v} `colors` musí být pole barev, ne {v} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1d3b12f63a..6be2b55e6b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5017,6 +5017,7 @@ theme Appearance Erscheinungsbild @msg every numbered name for it is taken in the Fonts folder alle nummerierten Namen dafür sind im Schriftenordner bereits vergeben @msg every numbered name for {name} is taken in the document's folder alle nummerierten Namen für {name} sind im Ordner des Dokuments bereits vergeben @msg No linked files to look for Keine verknüpften Dateien zum Suchen +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Die Verknüpfung befindet sich in einem Symbol, einem Diagrammdesign, einem Muster oder einer Deckkraftmaske und hat keinen Platz auf der Zeichenfläche # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Dienste diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 8467b8e831..3861f53fb0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5039,6 +5039,7 @@ digits Malayalam Μαλαγιάλαμ @msg every numbered name for it is taken in the Fonts folder όλα τα αριθμημένα ονόματά του χρησιμοποιούνται ήδη στον φάκελο γραμματοσειρών @msg every numbered name for {name} is taken in the document's folder όλα τα αριθμημένα ονόματα για το {name} χρησιμοποιούνται ήδη στον φάκελο εγγράφου @msg No linked files to look for Δεν υπάρχουν συνδεδεμένα αρχεία για αναζήτηση +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Ο σύνδεσμος βρίσκεται μέσα σε σύμβολο, σχεδιασμό γραφήματος, μοτίβο ή μάσκα αδιαφάνειας και δεν έχει θέση στον καμβά Hide VectorCraft Απόκρυψη VectorCraft Bring All to Front Μεταφορά όλων στο προσκήνιο Break Link Κατάργηση σύνδεσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 194ba2c602..bf9adc01b6 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5092,6 +5092,7 @@ axis Both Ambos @msg every numbered name for it is taken in the Fonts folder todos los nombres numerados para él ya existen en la carpeta Fonts @msg every numbered name for {name} is taken in the document's folder todos los nombres numerados para {name} ya existen en la carpeta del documento @msg No linked files to look for No hay archivos vinculados que buscar +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas El vínculo está dentro de un símbolo, un diseño de gráfico, un motivo o una máscara de opacidad y no tiene lugar en el lienzo # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Servicios diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e36c5e891e..3a193a980e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5300,6 +5300,7 @@ imageTrace Outline Ääriviiva @msg every numbered name for it is taken in the Fonts folder kaikki sen numeroidut nimet ovat jo käytössä Fonts-kansiossa @msg every numbered name for {name} is taken in the document's folder kaikki kohteen {name} numeroidut nimet ovat jo käytössä asiakirjan kansiossa @msg No linked files to look for Ei etsittäviä linkitettyjä tiedostoja +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Linkki on symbolin, kaaviomallin, kuvion tai peittävyysmaskin sisällä, eikä sillä ole paikkaa piirtoalueella @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` on vaiheviittaus {r}, jonka vain `run` ja `command_batch` ratkaisevat @msg `ids` must be an array of object ids, not {v} `ids` on oltava objektitunnusten taulukko, ei {v} @msg `colors` must be an array of colors, not {v} `colors` on oltava värien taulukko, ei {v} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 067845f493..5b7d36b7d1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5079,6 +5079,7 @@ axis Both Les deux @msg every numbered name for it is taken in the Fonts folder tous les noms numérotés pour ce fichier sont déjà pris dans le dossier Fonts @msg every numbered name for {name} is taken in the document's folder tous les noms numérotés pour {name} sont déjà pris dans le dossier du document @msg No linked files to look for Aucun fichier lié à rechercher +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Le lien se trouve dans un symbole, une conception de graphe, un motif ou un masque d’opacité et n’a pas de place sur le canevas # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Services diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 165e04ae7d..3c39e8cf19 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7192,6 +7192,7 @@ antiAlias Sharp शार्प @msg no library `{key}` (see {list}) कोई लाइब्रेरी `{key}` ({list} देखें) @msg No line breaks to remove हटाने के लिए कोई लाइन ब्रेक नहीं @msg No linked files to look for देखने के लिए कोई लिंक्ड फ़ाइल नहीं +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas लिंक किसी सिंबल, ग्राफ़ डिज़ाइन, पैटर्न या ओपेसिटी मास्क के अंदर है और कैनवास पर इसकी कोई जगह नहीं है @msg no Live Paint edge near that point उस बिंदु के पास कोई लाइव पेंट एज नहीं @msg no Live Paint face at that point उस बिंदु पर कोई लाइव पेंट फेस नहीं @msg no metafile format कोई मेटाफ़ाइल फ़ॉर्मैट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2ccf9d57bc..2420ee8319 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5139,6 +5139,7 @@ imageTrace Outline Körvonal @msg every numbered name for it is taken in the Fonts folder a Fonts mappában minden sorszámozott név foglalt hozzá @msg every numbered name for {name} is taken in the document's folder a dokumentum mappájában minden sorszámozott név foglalt: {name} @msg No linked files to look for Nincs keresendő csatolt fájl +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas A csatolás egy szimbólumban, diagrammintában, mintázatban vagy átlátszósági maszkban van, és nincs helye a vásznon @msg every search thread stopped on an internal error (please report this bug) minden keresési szál belső hibával leállt (kérjük, jelentsd ezt a hibát) @msg Expand Appearance: the selection has a basic appearance Megjelenés kibontása: a kijelölésnek alapmegjelenése van @msg Expand: no brush strokes selected Kibontás: nincs kijelölt ecsetvonás diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index be83d78b43..2ef7decb66 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5143,6 +5143,7 @@ axis Both Entrambi @msg every numbered name for it is taken in the Fonts folder tutti i nomi numerati per il file sono già usati nella cartella Fonts @msg every numbered name for {name} is taken in the document's folder tutti i nomi numerati per {name} sono già usati nella cartella del documento @msg No linked files to look for Nessun file collegato da cercare +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Il collegamento si trova in un simbolo, un design di grafico, un motivo o una maschera di opacità e non ha una posizione nell’area di disegno # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Servizi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b27c6d2698..c46278e818 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5210,6 +5210,7 @@ swatch Bright Violet ビビッドバイオレット @msg every numbered name for it is taken in the Fonts folder Fonts フォルダーでは、このファイルの番号付きの名前がすべて使われています @msg every numbered name for {name} is taken in the document's folder ドキュメントのフォルダーでは、{name} の番号付きの名前がすべて使われています @msg No linked files to look for 検索するリンクファイルがありません +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas このリンクはシンボル、グラフデザイン、パターン、または不透明マスクの中にあり、カンバス上に位置がありません @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` はステップ参照 {r} です。ステップ参照を解決できるのは `run` と `command_batch` だけです @msg `ids` must be an array of object ids, not {v} `ids` はオブジェクト ID の配列にしてください ({v} は使えません) @msg `colors` must be an array of colors, not {v} `colors` は色の配列にしてください ({v} は使えません) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 4ba40baab0..aee875402e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5110,6 +5110,7 @@ font-technology Variable ცვლადი @msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same მათზე არსებული ნახატი გვერდისგან {_1}%-ით განსხვავდება: მიუხედავად ამისა, ისინი რედაქტირების მონაცემებიდან აიღება @msg every numbered name for {name} is taken in the document's folder დოკუმენტის საქაღალდეში {name}-ის ყველა დანომრილი სახელი დაკავებულია @msg No linked files to look for მოსაძებნი დაკავშირებული ფაილები არ არის +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas ბმული სიმბოლოში, დიაგრამის დიზაინში, პატერნში ან გაუმჭვირვალობის ნიღაბშია და ტილოზე ადგილი არ აქვს Ruler Origin სახაზავების სათავე Reset Ruler Origin სახაზავების სათავის ჩამოყრა Artistic მხატვრული diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index c46ce6b4fa..ad8fb62588 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5137,6 +5137,7 @@ theme Appearance 외관 @msg every numbered name for it is taken in the Fonts folder 글꼴 폴더에서 이를 위한 번호 이름이 모두 사용 중입니다 @msg every numbered name for {name} is taken in the document's folder 문서 폴더에서 {name}을(를) 위한 번호 이름이 모두 사용 중입니다 @msg No linked files to look for 찾을 링크된 파일이 없습니다 +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas 링크가 심볼, 그래프 디자인, 패턴 또는 불투명 마스크 안에 있어 캔버스에 위치가 없습니다 @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id`는 단계 참조 {r}이며, `run`과 `command_batch`만 이를 해석합니다 @msg `ids` must be an array of object ids, not {v} `ids`는 {v}이(가) 아니라 개체 id 배열이어야 합니다 @msg `colors` must be an array of colors, not {v} `colors`는 {v}이(가) 아니라 색상 배열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a232ac4e8d..50e1dc63bc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5226,6 +5226,7 @@ imageTrace Outline Kontur @msg every numbered name for it is taken in the Fonts folder wszystkie numerowane nazwy dla niego są zajęte w folderze czcionek @msg every numbered name for {name} is taken in the document's folder wszystkie numerowane nazwy dla {name} są zajęte w folderze dokumentu @msg No linked files to look for Brak połączonych plików do wyszukania +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Łącze znajduje się w symbolu, wzorze wykresu, wzorku lub masce krycia i nie ma miejsca na obszarze roboczym @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` to odwołanie do kroku {r}, które rozwiązują tylko `run` i `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` musi być tablicą identyfikatorów obiektów, nie {v} @msg `colors` must be an array of colors, not {v} `colors` musi być tablicą kolorów, nie {v} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 68a225625d..322ad67da4 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5328,6 +5328,7 @@ axis Both Ambos @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise o texto de área em molduras baixas demais para uma linha da fonte em que aparece recebeu molduras mais altas ({_1}): senão o texto não apareceria @msg every numbered name for {name} is taken in the document's folder todos os nomes numerados para {name} já existem na pasta do documento @msg No linked files to look for Nenhum arquivo vinculado para procurar +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas O link está dentro de um símbolo, projeto de gráfico, padrão ou máscara de opacidade e não tem lugar na tela De-Interlace Desentrelaçar Eliminate Eliminar Create New Fields by Criar Novos Campos por diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a54d1eed2c..27b7b47e36 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5129,6 +5129,7 @@ axis Both Оба @msg every numbered name for it is taken in the Fonts folder все нумерованные имена для него уже заняты в папке Fonts @msg every numbered name for {name} is taken in the document's folder все нумерованные имена для {name} уже заняты в папке документа @msg No linked files to look for Нет связанных файлов для поиска +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Связь находится внутри символа, дизайна диаграммы, узора или непрозрачной маски и не имеет места на холсте # The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages. Services Службы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d0648b5946..d38c35c259 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4987,6 +4987,7 @@ axis Both Båda @msg every numbered name for it is taken in the Fonts folder alla numrerade namn för den är upptagna i mappen Typsnitt @msg every numbered name for {name} is taken in the document's folder alla numrerade namn för {name} är upptagna i dokumentets mapp @msg No linked files to look for Inga länkade filer att leta efter +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Länken finns i en symbol, en diagramdesign, ett mönster eller en opacitetsmask och har ingen plats på arbetsytan Services Tjänster Hide VectorCraft Göm VectorCraft Zoom Zoom diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 915a244b43..88f7341c35 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4825,6 +4825,7 @@ axis Both Her İkisi @msg every numbered name for it is taken in the Fonts folder bunun için numaralandırılmış her ad Yazı Tipleri klasöründe alınır @msg every numbered name for {name} is taken in the document's folder {name} için numaralandırılmış her ad belgenin klasöründe alınır @msg No linked files to look for Aranacak bağlantılı dosya yok +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Bağlantı bir sembolün, grafik tasarımının, desenin veya opaklık maskesinin içinde ve tuvalde yeri yok Services Hizmetler Hide VectorCraft VectorCraft'ı gizle Zoom Yakınlaştır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e8b5445a50..3a838f8bf8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5127,6 +5127,7 @@ axis Both Обидві @msg every numbered name for it is taken in the Fonts folder усі нумеровані імена для нього вже зайняті в папці Fonts @msg every numbered name for {name} is taken in the document's folder усі нумеровані імена для {name} уже зайняті в папці документа @msg No linked files to look for Немає пов’язаних файлів для пошуку +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Зв’язок міститься в символі, дизайні діаграми, візерунку або масці непрозорості й не має місця на полотні Services Служби Hide VectorCraft Приховати VectorCraft Zoom Масштаб diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 51681bfed5..5abcae4ee9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4966,6 +4966,7 @@ theme Appearance Giao diện @msg no library `{id}` không có thư viện `{id}` @msg no library `{key}` (see {list}) không có thư viện `{key}` (xem {list}) @msg No linked files to look for Không có tệp liên kết để tìm kiếm +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Liên kết nằm trong ký hiệu, thiết kế biểu đồ, họa tiết hoặc mặt nạ độ mờ và không có vị trí trên canvas @msg no Live Paint edge near that point không có cạnh tô trực tiếp gần điểm đó @msg no Live Paint face at that point không có mặt tô trực tiếp tại điểm đó @msg no native format không có định dạng gốc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d1e4de6bc6..9a63ddd188 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4899,6 +4899,7 @@ imageTrace Outline 轮廓 @msg every numbered name for it is taken in the Fonts folder 字体文件夹中所有带编号的名称均已被占用 @msg every numbered name for {name} is taken in the document's folder 文档所在文件夹中 {name} 的所有带编号的名称均已被占用 @msg No linked files to look for 没有要查找的链接文件 +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas 该链接位于符号、图表设计、图案或不透明度蒙版中,在画布上没有位置 @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` 是步骤引用 {r},只有 `run` 和 `command_batch` 能解析它 @msg `ids` must be an array of object ids, not {v} `ids` 必须是由对象 id 组成的数组,而不是 {v} @msg `colors` must be an array of colors, not {v} `colors` 必须是由颜色组成的数组,而不是 {v} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8e49ed109a..203910a663 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2668,6 +2668,7 @@ file-filter Templates 範本 @msg every numbered name for it is taken in the Fonts folder 字體資料夾中所有編號名稱都已被使用 @msg every numbered name for {name} is taken in the document's folder 文件所在資料夾中 {name} 的所有編號名稱都已被使用 @msg No linked files to look for 沒有要尋找的連結檔案 +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas 此連結位於符號、圖表設計、圖樣或不透明度遮色片中,在畫布上沒有位置 @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` 是步驟參照 {r},只有 `run` 和 `command_batch` 能解析它 @msg `ids` must be an array of object ids, not {v} `ids` 必須是由物件 id 組成的陣列,而非 {v} @msg `colors` must be an array of colors, not {v} `colors` 必須是由顏色組成的陣列,而非 {v} diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 38f9848760..5fa9199f19 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -8,6 +8,10 @@ //! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, thumbnail size //! and Show in Folder. //! +//! Images and placed documents in opacity-mask art and in the art of symbols, graph designs and +//! patterns are listed after the layers' own, one row each; the canvas can't select them, so a +//! click picks such a row in the panel, and the buttons act on it as on any other. +//! //! Everything runs through the `links.*` commands (`links.editOriginal` and `links.reveal` are UI //! commands: they hand the file to the system). @@ -52,6 +56,8 @@ struct Cache { at: f64, list: Value, info: Option<(u64, Value)>, + /// The objects of the rows outside the layer tree, by id, for their thumbnails. + nested: Vec<(u64, std::sync::Arc)>, } fn options(ctx: &egui::Context) -> Options { @@ -69,13 +75,27 @@ fn set_options(ctx: &egui::Context, f: impl FnOnce(&mut Options)) { fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option { let st = app.session.active()?; let key = Some((st.uid, st.revision, o.show, o.sort)); - let first = selected_images(app).first().copied(); + let first = selected_links(app, ctx).first().copied(); let now = ctx.input(|i| i.time); let mut c: Cache = pstate(ctx, "links-cache"); let stale = c.key != key || now - c.at > RECHECK; if stale { c.list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort })).ok()?; (c.key, c.at) = (key, now); + // One pass over the stored art for the rows outside the layer tree, not one per frame. + let mut want: std::collections::HashSet = + c.list["links"].as_array().into_iter().flatten().filter(|r| nested_row(r)).filter_map(|r| r["id"].as_u64()).collect(); + c.nested.clear(); + if !want.is_empty() + && let Some(st) = app.session.active() + { + st.doc.visit_stored_arcs(|n, place| { + if !place.in_layers() && want.remove(&n.id.0) { + c.nested.push((n.id.0, std::sync::Arc::clone(n))); + } + }); + c.nested.sort_by_key(|(id, _)| *id); + } } let want = first.filter(|_| o.info); if stale || c.info.as_ref().map(|(id, _)| *id) != want { @@ -96,6 +116,50 @@ fn selected_images(app: &VectorcraftApp) -> Vec { st.selection.objects.iter().filter(|id| image(id)).map(|id| id.0).collect() } +/// Is row `r` of an object outside the layer tree (in opacity-mask art or the art of a symbol, +/// graph design or pattern), which the canvas can't select? +fn nested_row(r: &Value) -> bool { + r["owner"].is_object() +} + +/// The active document's uid and the ids of its selected objects. +fn canvas_selection(app: &VectorcraftApp) -> Option<(u64, Vec)> { + app.session.active().map(|st| (st.uid, st.selection.objects.iter().map(|id| id.0).collect())) +} + +/// The rows outside the layer tree picked in the panel, with the canvas selection +/// ([`canvas_selection`]) they were picked with. +type NestedPicks = Option<((u64, Vec), Vec)>; + +/// The rows outside the layer tree picked in the panel, in the active document. A change of the +/// canvas selection, or another document, drops them (the panel looks every frame). +fn nested_picks(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { + let picks: NestedPicks = pstate(ctx, "links-nested"); + let Some((at, ids)) = picks else { return vec![] }; + if Some(&at) == canvas_selection(app).as_ref() { + return ids; + } + set_pstate::(ctx, "links-nested", None); + vec![] +} + +/// Keep `ids` as the rows picked in the panel, with the canvas selection as it is now. +fn set_nested_picks(app: &VectorcraftApp, ctx: &egui::Context, ids: Vec) { + set_pstate(ctx, "links-nested", canvas_selection(app).map(|at| (at, ids))); +} + +/// The ids of the selected rows: the selected images and placed documents, then the rows outside +/// the layer tree picked in the panel. +fn selected_links(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { + let mut ids = selected_images(app); + for id in nested_picks(app, ctx) { + if !ids.contains(&id) { + ids.push(id); + } + } + ids +} + /// The rows of `list` whose image is selected. fn selected_rows<'a>(list: &'a Value, selected: &[u64]) -> Vec<&'a Value> { list["links"].as_array().into_iter().flatten().filter(|r| r["id"].as_u64().is_some_and(|id| selected.contains(&id))).collect() @@ -170,9 +234,14 @@ fn relink_to_picked_folder(app: &mut VectorcraftApp, ids: Vec) { }); } -/// Select image `id` and scroll it into view. +/// Select image `id` and scroll it into view; one outside the layer tree only says that it has no +/// place on the canvas. pub(crate) fn go_to(app: &mut VectorcraftApp, id: u64) { let Ok(r) = app.run("links.goTo", json!({ "id": id })) else { return }; + if r["onCanvas"] == false { + app.status("The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas"); + return; + } let b: Vec = r["bounds"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect(); if let (&[x0, y0, x1, y1], Some(v)) = (&b[..], app.view_mut()) { v.center = vectorcraft_geom::Point::new((x0 + x1) / 2.0, (y0 + y1) / 2.0); @@ -290,25 +359,46 @@ fn status_tip(r: &Value) -> String { /// Ctrl/Cmd adds or removes it, and Shift selects the images of the rows from the last row clicked /// without Shift in this document to it, or with Ctrl/Cmd adds them to the selection. A /// Shift-click while that row is not shown, or after the last click was in another document, acts -/// as a click without Shift. +/// as a click without Shift. Rows outside the layer tree are picked in the panel itself, as the +/// canvas can't select them; a click without Ctrl/Cmd replaces both kinds of selection. fn click(app: &mut VectorcraftApp, ctx: &egui::Context, rows: &[Value], id: u64, m: egui::Modifiers) { let Some(uid) = app.session.active().map(|st| st.uid) else { return }; let anchor: Option<(u64, u64)> = pstate(ctx, "links-anchor"); let at = |id: u64| rows.iter().position(|r| r["id"].as_u64() == Some(id)); + let nested = |r: &Value| nested_row(r).then(|| r["id"].as_u64()).flatten(); + let mut picks = if m.command { nested_picks(app, ctx) } else { vec![] }; if m.shift && let Some((_, a)) = anchor.filter(|(doc, _)| *doc == uid) && let (Some(i), Some(j)) = (at(a), at(id)) { - let range: Vec = rows.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().filter_map(|r| r["id"].as_u64()).collect(); - app.run(if m.command { "select.add" } else { "select.set" }, json!({ "ids": range })).ok(); + let range = rows.get(i.min(j)..=i.max(j)).unwrap_or_default(); + let canvas: Vec = range.iter().filter(|r| !nested_row(r)).filter_map(|r| r["id"].as_u64()).collect(); + picks.extend(range.iter().filter_map(nested).filter(|id| !picks.contains(id)).collect::>()); + app.run(if m.command { "select.add" } else { "select.set" }, json!({ "ids": canvas })).ok(); + set_nested_picks(app, ctx, picks); return; } set_pstate(ctx, "links-anchor", Some((uid, id))); + let row = rows.iter().find(|r| r["id"].as_u64() == Some(id)); + if row.is_some_and(nested_row) { + match picks.iter().position(|p| *p == id) { + Some(i) if m.command => { + picks.remove(i); + } + _ => picks.push(id), + } + if !m.command { + app.run("select.set", json!({ "ids": [] })).ok(); + } + set_nested_picks(app, ctx, picks); + return; + } if m.command { app.run("select.toggle", json!({ "id": id })).ok(); } else { app.run("select.set", json!({ "ids": [id] })).ok(); } + set_nested_picks(app, ctx, picks); } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -322,7 +412,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { return }; let doc = st.doc.clone(); let thumbs = super::layers::ThumbSource::of(app, st, &doc); - let selected = selected_images(app); + let selected = selected_links(app, ui.ctx()); let rows: &[Value] = cache.list["links"].as_array().map_or(&[], Vec::as_slice); let mut clicked: Option<(u64, egui::Modifiers, bool)> = None; widgets::list_box(ui, |ui| { @@ -354,7 +444,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if o.thumb > 0.0 { let tr = egui::Rect::from_min_size(egui::pos2(x, rect.center().y - o.thumb / 2.0), vec2(o.thumb, o.thumb)); ui.painter().rect_filled(tr, 0.0, egui::Color32::WHITE); - if let Some(n) = super::layers::node_arc(&doc, NodeId(id)) { + let node = if nested_row(r) { + cache + .nested + .binary_search_by_key(&id, |(n, _)| *n) + .ok() + .and_then(|i| cache.nested.get(i)) + .map(|(_, n)| std::sync::Arc::clone(n)) + } else { + super::layers::node_arc(&doc, NodeId(id)) + }; + if let Some(n) = node { super::layers::real_thumb(ui, &thumbs, &n, tr); } ui.painter().rect_stroke(tr, 0.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); @@ -411,7 +511,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if widgets::icon_button_enabled(ui, "pencil", tl!("Edit Original"), false, can_edit, 24.0).clicked() { - crate::menus::invoke(app, "links.editOriginal", json!({})); + crate::menus::invoke(app, "links.editOriginal", file_row(&sel)); } if widgets::icon_button_enabled(ui, "rotate-cw", tl!("Update Link"), false, !modified.is_empty(), 24.0).clicked() { let r = app.run("links.update", json!({ "ids": modified })); @@ -452,6 +552,15 @@ fn break_link(app: &mut VectorcraftApp, ids: Vec) { }); } +/// The params of Edit Original and Show in Folder for the selected rows `sel`: the first linked +/// row whose file is there (rows outside the layer tree included), else none (the selection's). +fn file_row(sel: &[&Value]) -> Value { + match ids(sel, |r| r["linked"] == true && !status_is(r, "missing")).first() { + Some(id) => json!({ "id": id }), + None => json!({}), + } +} + /// Pick-a-file actions need a file dialog (the desktop app). fn can_pick(app: &VectorcraftApp) -> bool { app.services.pick_open.is_some() @@ -538,7 +647,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). let list = pstate::(ui.ctx(), "links-cache").list; - let selected = selected_images(app); + let selected = selected_links(app, ui.ctx()); let sel = selected_rows(&list, &selected); let linked = ids(&sel, |r| r["linked"] == true); let embedded: Vec<&Value> = sel.iter().copied().filter(|r| status_is(r, "embedded")).collect(); @@ -563,7 +672,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); } if menu_item(ui, tl!("Edit Original"), sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")), false) { - crate::menus::invoke(app, "links.editOriginal", json!({})); + crate::menus::invoke(app, "links.editOriginal", file_row(&sel)); } ui.separator(); if menu_item(ui, tl!("Embed Image(s)"), !linked.is_empty(), false) { @@ -594,7 +703,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, "ui.placementOptionsDialog", json!({ "ids": ids(&sel, |_| true) })); } if menu_item(ui, tl!("Show in Folder"), sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")), false) { - crate::menus::invoke(app, "links.reveal", json!({})); + crate::menus::invoke(app, "links.reveal", file_row(&sel)); } ui.separator(); // Select Linked, Embedded, Missing and Modified: every such image in the document, not only diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 215cf7148a..be5e17e374 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -132,6 +132,52 @@ fn shift_click_selects_a_range_of_links_and_ctrl_click_toggles_one() { assert_eq!(selected(&app), id(&[3])); } +/// A linked image kept only in a symbol's art has a row of its own: a click picks it in the panel +/// (the canvas selection is cleared), Link Info shows it, Ctrl/Cmd-click adds an image in the +/// layers, a change of the canvas selection drops the pick, and Go To clears the selection and +/// says it has no place on the canvas. +#[test] +fn a_link_inside_a_symbol_is_listed_and_picked_in_the_panel() { + let dir = Folder::new("nested"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let inside = dir.file("inside.png", &png(30, 20)); + let id = app.run("file.place", json!({"path": inside, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("symbol.new", json!({"name": "Mark", "ids": [id]})).unwrap(); + app.run("edit.clear", json!({"ids": selected(&app)})).unwrap(); + let outside = dir.file("layer.png", &png(20, 20)); + let layer = app.run("file.place", json!({"path": outside, "at": [300, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + let list = app.run("links.list", json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == "inside.png").unwrap_or_else(|| panic!("{list}")).clone(); + assert_eq!(row["owner"]["kind"], "symbol", "{list}"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let shown = |app: &mut VectorcraftApp, time: f64| -> Vec { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show).into_iter().map(|(t, _)| t).collect() + }; + assert!(shown(&mut app, 0.5).iter().any(|t| t == "20 × 20 px"), "Link Info of the selected image in the layers"); + click_row(&mut app, &ctx, "inside.png", egui::Modifiers::NONE, 1.0); + assert!(selected(&app).is_empty(), "the canvas can't select it"); + assert!(shown(&mut app, 1.5).iter().any(|t| t == "30 × 20 px"), "Link Info of the symbol's image"); + click_row(&mut app, &ctx, "layer.png", egui::Modifiers::COMMAND, 2.0); + assert_eq!(selected(&app), [layer]); + // Both rows are selected until the canvas selection changes: then the panel's pick goes too. + click_row(&mut app, &ctx, "layer.png", egui::Modifiers::COMMAND, 3.0); + assert!(selected(&app).is_empty()); + assert!(shown(&mut app, 3.5).iter().any(|t| t == "30 × 20 px"), "the symbol's image is still picked"); + app.run("select.set", json!({"ids": [layer]})).unwrap(); + assert!(shown(&mut app, 4.0).iter().any(|t| t == "20 × 20 px")); + app.run("select.set", json!({"ids": []})).unwrap(); + let text = shown(&mut app, 4.5); + assert!(!text.iter().any(|t| t == "30 × 20 px" || t == "20 × 20 px"), "nothing is picked: {text:?}"); + // Go To clears the selection and says the link has no place on the canvas. + app.run("select.set", json!({"ids": [layer]})).unwrap(); + super::links::go_to(&mut app, row["id"].as_u64().unwrap()); + assert_eq!(app.ui.status, "The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas"); + assert!(selected(&app).is_empty(), "the image in the layers is no longer selected"); +} + #[test] fn an_empty_document_shows_how_to_add_images() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index 2c8afc7aea..0837f48fb4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6403,8 +6403,8 @@ path isn't followed) when it isn't. The desktop app also checks the active docum comes back to the front, following the same preference. `links.check` reports every link's `status` (`ok`, `modified`, `missing`), `links.update {ids?}` reads modified files again and `links.relink {ids?, path | folder}` points images at another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. -`links.relink`'s `scope` picks which links take the new file (Relink's Replace choice): `selected` (the default) relinks `ids`; `all` also relinks every other object in the layers linked to the same file as -one of them; `missingInFolder` relinks `ids` to `path`, then every other missing link to the file of its name in +`links.relink`'s `scope` picks which links take the new file (Relink's Replace choice): `selected` (the default) relinks `ids`; `all` also relinks every other stored object linked to the same file as +one of them, in the layers, opacity-mask art, symbols, graph designs and patterns; `missingInFolder` relinks `ids` to `path`, then every other missing link to the file of its name in `path`'s folder, and lists the names not there in `notFound` (with `copy`, only missing images are looked for); `each` takes `paths: [{ids, path}]` in place of `ids`, `path` and `folder` and relinks each link to its own file. An unknown scope, `paths` without `each`, `each` with `ids`, `path` or `folder`, an entry without `path` or `ids`, an id in two entries and `missingInFolder` with `folder` are @@ -6412,8 +6412,10 @@ errors, and nothing is relinked. Each call is one undo step. The Links panel's R (`ui.relinkDialog`) with a Replace menu of these four choices. A PNG, JPEG, another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. `links.update`, and `document.open` when it reads a modified file, also read the file again for the images and placed -documents inside symbols, graph designs, patterns and opacity masks that show the same content (by default also for -those that only that art shows); they have no ids, so the results do not list them. Saving a document also reads it +documents inside symbols, graph designs, patterns and opacity masks that show the same content. Those objects have ids +of their own: `links.list`, `links.check`, `links.findFiles`, the `missingLinks`, `modifiedLinks` and `updatedLinks` +rows and the link watch list them, and every `links.*` command takes their ids. Opening a document gives an object +there whose id is 0 or already used by another object a new id, and the next save writes it. Saving a document also reads it again for the placed documents of it inside that art in the other open documents. A PNG, JPEG, GIF or WebP file whose pixels can't be read is not shown: `links.relink` fails with "the image's pixels can't be read", and `links.update`, or `document.open` when it reads the file, lists it as missing, its images keeping what they @@ -6653,8 +6655,11 @@ listed in `warnings`. Binary DXF and DWG files answer an error saying to save th ## Links panel `links.list {show?: all|missing|modified|embedded, sort?: name|kind|status}` lists every image in the layers, top -first, as the Links panel does: `{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, -pixelHeight, path?, found?, page?, preview?, note?}` (`note`: the image takes more than the decode allowance, 2 GiB +first, as the Links panel does, then every image and placed document in opacity-mask art and in the art of symbols, +graph designs and patterns, one row per stored object (never one per symbol instance or pattern tile): `{id, name, +linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?, page?, preview?, note?, +owner?}` (`owner`, for an object outside the layer tree: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`, +`maskOf` naming the object whose opacity mask holds it; `note`: the image takes more than the decode allowance, 2 GiB or 512 MiB in the web app, as RGBA or as decoded, and it is drawn at the largest size within the allowance ("shown at reduced size"; the document keeps the whole file) or, when it can't be read that way or has more pixels than the allowance has bytes, drawn as a crossed gray box on the canvas and left out of exports ("too large to draw"); `document.open` and `file.place` say the same in their `warnings`). `links.info {id?}` is the Link Info: `image.info`'s fields plus @@ -6662,7 +6667,8 @@ allowance has bytes, drawn as a crossed gray box on the canvas and left out of e counter-clockwise), `placement` and, for a linked file, `fileName`, `location`, `fileSize`, `created`, `modified`. With automation read roots, a file outside them has no `path` or `found` in `links.list` and `links.check`, and no `link`, `path`, `location`, `fileSize` or `modified` in `links.info`; its row keeps the file's name. -`links.goTo {id}` selects an image; `links.embed {ids?}` keeps linked files' pixels in the document (an image whose +`links.goTo {id}` selects an image (`onCanvas: true`); for an object outside the layer tree it clears the selection and +returns `{id, onCanvas: false, owner}`, and the panel says the link has no place on the canvas. `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. `links.placementOptions {ids?, preserve?: transforms|bounds|fileDimensions|fit|fill, align?: topLeft…bottomRight, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1ce5c5fda5..6bcf0ac446 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1629,6 +1629,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. - On Windows, a link on a drive mapped to a network share other than the document's (`Y:\…`) is missing, with the reason that the path is on another computer, as a link stored with that share's own path is; links on this computer's drives and on the document's share are followed. - In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one. + - Linked images and placed documents kept only in symbols, graph designs, patterns or opacity masks are listed in the Links panel after the layers' own, one row per stored object, with their status in its Missing and Modified filters, in Check Links, in the missing and modified files reported when a document opens, in the link watch and in Find in Folder; Relink, Update, Embed, Placement Options and Link Info act on them, and Go To says they have no place on the canvas. Opening a document gives such an object whose id is 0 or repeats another object's a new id. - Linked files another app changes while their document is open follow Preferences › File Handling › Update Links, as they do when it opens: Automatically reads them again (an Update Links undo step), Ask When Modified offers to, Manually leaves them modified in the Links panel. The desktop app compares the active document’s linked files by size and modification time every two seconds and when its window comes back to the front, on a worker thread; a file still being written is tried again (`links.updateChanged`). - A look at the linked files whose worker thread ends without a result, such as after a panic, no longer stops later looks: the app clears it, stops asking for a frame every 100 ms, and the next look starts on schedule (`crates/engine/src/tests/linkwatch.rs`, `crates/ui-egui/src/tests/place.rs`). - Import and paste, 2026-10-13: a multi-artboard `.ai` with notes beside its artboards opens from its editing data, a page's art past its artboard no longer lying over the page before it (#1528); a `.ai` gradient whose stops are listed upwards keeps each midpoint on the stop that starts its part of the ramp (#1530); SVG text on a path follows basic shapes (circle, ellipse, rect, line, polyline, polygon) as their SVG 2 equivalent paths (#1531, fixes #1527); PDFs whose alpha soft masks are drawn as images import with the mask instead of empty art (#1551); EPS and PostScript type set in Type 42 (TrueType) fonts imports at its size instead of 1000 times too large (#1553); PDF and EPS import keep a clipping path whose bounding box covers the page but whose shape doesn't (#1544, fixes #1542). Opening or placing a file with an image too large to decode says so, and the Links panel shows it on the row (#1540, part of #1479). Paste takes a PDF or EPS another app copied as editable vector art: from the macOS pasteboard (with SVG), EPS on Windows beside PDF, and `.eps` files copied in a file manager, with the new command `clipboard.importEps` (#1538, fixes #1499). From a7c82ac7f2598f1ebc26422c21fbdad335ef44c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 21:24:12 -0800 Subject: [PATCH 02/28] Links: test a DCS image in a symbol updated and relinked by its id The symbol's image keeps following its DCS file's clipping path when it is updated by the id links.list gives it, and loses that path when it is relinked to a plain image. --- crates/engine/src/tests/dcs.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index 2801432a0a..8a75da8208 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -326,6 +326,31 @@ fn update_link_takes_the_files_clipping_path_into_symbols_too() { assert_eq!(symbol_clip_width(&s, "Pic"), None); } +#[test] +fn update_and_relink_by_id_keep_the_clipping_path_of_a_dcs_image_in_a_symbol() { + let dir = temp_dir("symbol-clip-by-id"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [r["ids"][0]] })).unwrap(); + let list = s.execute("links.list", &json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image is listed"); + let id = row["id"].as_u64().unwrap(); + assert_eq!(row["format"], "DCS", "{list}"); + let before = symbol_clip_width(&s, "Pic").expect("the file's clipping path"); + // The composite now drawn through the left quarter of the page (same length). + let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, text.as_bytes()).unwrap(); + assert_eq!(s.execute("links.update", &json!({ "ids": [id] })).unwrap()["updated"], json!([id])); + let after = symbol_clip_width(&s, "Pic").expect("still clipped"); + assert!((after - before / 2.0).abs() < 1e-6, "the symbol's clipping path follows the file: {before} → {after}"); + // Relinked by its id to a plain image: the DCS file's clipping path goes. + let png = dir.join("plain.png"); + image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap(); + s.execute("links.relink", &json!({ "ids": [id], "path": png.to_string_lossy() })).unwrap(); + assert_eq!(symbol_clip_width(&s, "Pic"), None); +} + #[test] fn a_file_that_lost_its_clipping_path_unclips_the_image() { let dir = temp_dir("update-lost-clip"); From c2ed2dd3a93dc9d322f309cc132aca06b34559ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 21:38:46 -0800 Subject: [PATCH 03/28] Links: Find in Folder copies the files of images in symbols and patterns With Copy into the document's folder, an image picked in the Links panel by the id of an object in a symbol, graph design, pattern or opacity mask was relinked to the found file instead of a copy, because the check for an image looked only in the layers. --- crates/ui-egui/src/dialogs/find_links.rs | 5 ++-- .../ui-egui/src/dialogs/find_links/tests.rs | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/find_links.rs b/crates/ui-egui/src/dialogs/find_links.rs index 05f0e85b60..2e99f5e97e 100644 --- a/crates/ui-egui/src/dialogs/find_links.rs +++ b/crates/ui-egui/src/dialogs/find_links.rs @@ -112,11 +112,12 @@ pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option bool { let Some(id) = id.as_u64() else { return false }; let st = app.session.active(); - st.and_then(|st| st.doc.node(vectorcraft_doc::NodeId(id))).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_))) + st.and_then(|st| st.doc.stored_node(vectorcraft_doc::NodeId(id))).is_some_and(|(n, _)| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_))) } /// Make the dialog's document the active one: it may be another tab's. diff --git a/crates/ui-egui/src/dialogs/find_links/tests.rs b/crates/ui-egui/src/dialogs/find_links/tests.rs index 4722b8b327..0b618c7e6f 100644 --- a/crates/ui-egui/src/dialogs/find_links/tests.rs +++ b/crates/ui-egui/src/dialogs/find_links/tests.rs @@ -255,6 +255,35 @@ fn copy_into_the_documents_folder_copies_before_relinking() { assert!(!frame(&mut app).contains("Copy into the document's folder")); } +/// Copy into the document's folder copies the file of an image in a symbol's art too, picked in the +/// Links panel by its id. +#[test] +fn copy_takes_an_image_in_a_symbol_into_the_documents_folder() { + let root = folder("copy-symbol"); + let mut app = app_for(&root); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let orig = at(&root, "orig/a.png"); + write(&orig, &png(3)); + let placed = app.run("file.place", json!({"path": orig})).unwrap()["ids"][0].clone(); + app.run("symbol.new", json!({"name": "Mark", "ids": [placed]})).unwrap(); + let doc = at(&root, "doc/doc.vectorcraft"); + std::fs::create_dir_all(doc.parent().unwrap()).unwrap(); + app.run("document.save", json!({"path": doc})).unwrap(); + write(&at(&root, "found/a.png"), &png(3)); + let list = app.run("links.list", json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image"); + app.run("ui.findLinksInFolder", json!({"folder": root.join("found"), "ids": [row["id"]]})).unwrap(); + searched(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("copy".into(), json!(true)); + let r = super::super::confirm(&mut app).unwrap(); + assert_eq!((r["relinked"].as_array().map(Vec::len), &r["failed"]), (Some(1), &json!([])), "{r}"); + let copy = at(&root, "doc/a.png"); + assert_eq!(std::fs::read(©).unwrap(), png(3)); + let list = app.run("links.list", json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().unwrap(); + assert_eq!(row["path"], json!(copy), "{list}"); +} + /// With Copy into the document's folder, a placed document is relinked where its file is. #[test] fn copy_leaves_placed_documents_where_they_are() { From 072b68583a33ee25df466ac286c182ae09fede39 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 22:50:22 -0800 Subject: [PATCH 04/28] Place: placing the same file again shares the symbols and patterns it brought Symbol and pattern art copied in by a placement takes ids of the document's own, so the next placement of the same file compared it with the file's art, found the ids different and added Star 2, Dots 2 and so on. Definitions are now compared by what their art draws, whatever its ids. A symbol, pattern or brush whose art uses an image, symbol, pattern, brush or swatch that comes in under another name is copied under a free name instead of shared. --- crates/engine/src/cmd/place/adopt.rs | 100 ++++++++++++++++++++++++--- crates/engine/src/tests/place.rs | 68 ++++++++++++++++++ 2 files changed, 160 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 0a0f08d3c1..9cd28b7e25 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use vectorcraft_brush::{Brush, BrushKind}; use vectorcraft_color::Paint; -use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind}; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol}; use super::unique_name; @@ -118,11 +118,12 @@ impl Used { type Renames = BTreeMap, bool)>; /// Names in `dst` for the `used` definitions of `src` (`def`): the same name when `dst` has none -/// (copied) or an equal one (shared), else a free variant (`taken`, copied). -fn names( +/// (copied) or one that is the `same` (shared), else a free variant (`taken`, copied). +fn names( used: &[String], def: impl Fn(&str) -> Option, existing: impl Fn(&str) -> Option, + same: impl Fn(&T, &T) -> bool, taken: impl Fn(&str) -> bool, ) -> Renames { let mut out = Renames::new(); @@ -130,7 +131,7 @@ fn names( let Some(d) = def(name) else { continue }; let entry = match existing(name) { None => (Some(name.clone()), true), - Some(e) if e == d => (Some(name.clone()), false), + Some(e) if same(&e, &d) => (Some(name.clone()), false), Some(_) => { (Some(unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || out.values().any(|(n, _)| n.as_deref() == Some(c)))), true) } @@ -140,6 +141,65 @@ fn names( out } +/// `n` as `dst` would copy it in ([`Document::reid`]), with the ids a document of its own gives it: +/// art copied in once, which differs from the file's only in its ids, compares equal to the file's. +fn canon(dst: &Document, n: &Node) -> Node { + let mut own = Document::new(0.0, 0.0); + // Pixels the art carries take a key `dst` doesn't use for other pixels, as they do in `dst`. + let mut keys = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| { + if let NodeKind::Image(im) = &c.kind + && im.pixels.is_some() + { + keys.push(im.key.clone()); + } + }); + for (k, blob) in &dst.images { + if keys.iter().any(|key| k == key || k.strip_prefix(key.as_str()).is_some_and(|rest| rest.starts_with('-'))) { + own.images.insert(k.clone(), blob.clone()); + } + } + own.reid(n) +} + +/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])? +fn same_symbol(dst: &Document, a: &Symbol, b: &Symbol) -> bool { + let own = |s: &Symbol| Symbol { art: Arc::new(canon(dst, &s.art)), ..s.clone() }; + own(a) == own(b) +} + +/// Do patterns `a` and `b` draw the same, whatever ids their art has ([`canon`])? +fn same_pattern(dst: &Document, a: &PatternDef, b: &PatternDef) -> bool { + let bare = |p: &PatternDef| PatternDef { art: vec![], ..p.clone() }; + bare(a) == bare(b) && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| canon(dst, x) == canon(dst, y)) +} + +/// Does art `a` use a resource that `m` (images, symbols, patterns, brushes, swatches) gives +/// another name, or a swatch whose link `m` drops? +fn uses_moved(a: &Node, m: [&Renames; 5]) -> bool { + let moved = |map: &Renames, k: &str| map.get(k).is_some_and(|(new, _)| new.as_deref() != Some(k)); + let (mut a, mut any) = (a.clone(), false); + refs(&mut a, &mut |r| { + any |= match r { + Ref::Image(k) => moved(m[0], k), + Ref::Symbol(k) => moved(m[1], k), + Ref::Pattern(k) => moved(m[2], k), + Ref::Brush(k) => moved(m[3], k), + Ref::Swatch(link) => link.as_deref().is_some_and(|k| moved(m[4], k)), + } + }); + any +} + +/// Copy each of `shared` in `map` under a free name, as [`names`] does for a definition `dst` +/// holds differently. +fn unshare(map: &mut Renames, shared: &[String], used: &[String], taken: impl Fn(&str) -> bool) { + for name in shared { + let free = unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || map.values().any(|(n, _)| n.as_deref() == Some(c))); + map.insert(name.clone(), (Some(free), true)); + } +} + /// The renamed resources whose definitions are copied: (name in `src`, name in `dst`). fn copies(m: &Renames) -> Vec<(&str, &str)> { m.iter().filter(|(_, (_, copy))| *copy).filter_map(|(old, (new, _))| Some((old.as_str(), new.as_deref()?))).collect() @@ -194,14 +254,17 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { } } - let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |c| dst.images.contains_key(c)); - let symbols = names( + let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c)); + // Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it + // draws: placing the same file again shares what the first placement brought. + let mut symbols = names( &used.symbols, |n| src.symbols.iter().find(|s| s.name == n), |n| dst.symbols.iter().find(|s| s.name == n), + |a, b| same_symbol(dst, a, b), |c| dst.symbols.iter().any(|s| s.name == c), ); - let patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |c| dst.pattern(c).is_some()); + let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some()); // A swatch the document defines differently isn't renamed (that would add look-alike swatches): // the colours linked to it keep their look, unlinked. let swatches: Renames = used @@ -236,12 +299,33 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { any }; let mut dst_brushes = vectorcraft_brush::library(dst); - let brushes = names( + let mut brushes = names( &used.brushes, |n| src_brushes.iter().find(|b| b.name == n).map(|b| (b, moves_art(b))), |n| dst_brushes.iter().find(|b| b.name == n).map(|b| (b, false)), + |a, b| a == b, |c| dst_brushes.iter().any(|b| b.name == c), ); + // Likewise a symbol, pattern or brush whose art uses a resource that moves isn't the + // document's of that name: it is copied under a free name, which can move what uses it in turn. + loop { + let maps = [&images, &symbols, &patterns, &brushes, &swatches]; + let shared = |map: &Renames| map.iter().filter(|(_, (_, copy))| !*copy).map(|(k, _)| k.clone()).collect::>(); + let sym: Vec = + shared(&symbols).into_iter().filter(|n| src.symbols.iter().any(|s| s.name == *n && uses_moved(&s.art, maps))).collect(); + let pat: Vec = + shared(&patterns).into_iter().filter(|n| src.pattern(n).is_some_and(|p| p.art.iter().any(|a| uses_moved(a, maps)))).collect(); + let bru: Vec = shared(&brushes) + .into_iter() + .filter(|n| src_brushes.iter().find(|b| b.name == *n).is_some_and(|b| brush_art(&mut b.clone()).into_iter().any(|a| uses_moved(a, maps)))) + .collect(); + if sym.is_empty() && pat.is_empty() && bru.is_empty() { + break; + } + unshare(&mut symbols, &sym, &used.symbols, |c| dst.symbols.iter().any(|s| s.name == c)); + unshare(&mut patterns, &pat, &used.patterns, |c| dst.pattern(c).is_some()); + unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c)); + } let mut rename = |r: Ref| { let (map, k) = match r { diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 455471dbb1..ab80255376 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -689,6 +689,74 @@ fn placed_art_brings_its_symbols_and_patterns_with_ids_of_the_documents_own() { assert_eq!(unique.len(), ids.len(), "{ids:?}"); } +/// Placing the same file again shares the symbols and patterns the first placement brought: their +/// art differs from the file's only in its ids, so no `Star 2` or `Dots 2` joins the document. +#[test] +fn placing_the_same_art_again_shares_its_symbols_and_patterns() { + let mut src = session(); + src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star"})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + let mut s = session(); + let counts = |s: &Session| { + let doc = &s.doc().unwrap().doc; + (doc.symbols.len(), doc.patterns.len()) + }; + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let once = counts(&s); + for _ in 0..2 { + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + } + assert_eq!(counts(&s), once); + let doc = &s.doc().unwrap().doc; + assert!(!doc.symbols.iter().any(|x| x.name == "Star 2") && doc.pattern("Dots 2").is_none()); +} + +/// A symbol whose art matches the document's own but uses a pattern the document defines +/// differently is not shared: it comes in under a free name, using the pattern it brings. +#[test] +fn placed_art_does_not_share_a_symbol_whose_pattern_moves() { + let mut src = session(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star", "ids": [tile.0]})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + let mut s = session(); + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + // The document's "Dots" changes; its "Star" still matches the file's. + let st = s.doc_mut().unwrap(); + let d = Arc::make_mut(&mut st.doc); + let dots = d.pattern_mut("Dots").unwrap(); + dots.tile = Rect::new(0.0, 0.0, 50.0, 50.0); + let r = place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let mut symbol = None; + node(&s, &r["ids"][0]).walk(&mut |n| { + if let NodeKind::SymbolInstance { symbol: name, .. } = &n.kind { + symbol = Some(name.clone()); + } + }); + assert_eq!(symbol.as_deref(), Some("Star 2")); + let doc = &s.doc().unwrap().doc; + let star2 = doc.symbols.iter().find(|x| x.name == "Star 2").unwrap(); + let mut fills = vec![]; + star2.art.walk(&mut |n| { + fills.extend(n.appearance.items.iter().filter_map(|i| match i { + AppearanceItem::Fill(f) => match &f.paint { + Paint::Pattern { pattern, .. } => Some(pattern.clone()), + _ => None, + }, + _ => None, + })) + }); + assert_eq!(fills, ["Dots 2"]); +} + #[test] fn placed_art_brings_its_brushes_renaming_on_conflict() { // The file: a path with its own brush, and one with a brush the defaults hold. From 64241978ec9e2814135382782e19bf9192eb1d02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 22:50:22 -0800 Subject: [PATCH 05/28] Links: a nested row's tooltip names the symbol, graph design, pattern or mask holding it Two rows of the same file in different symbols showed the same name, thumbnail and status. The tooltip of a row outside the layer tree now adds the symbol, graph design or pattern whose art holds the image, and the object whose opacity mask holds it. --- crates/ui-egui/src/panels/links.rs | 33 ++++++++++++++++++++++-- crates/ui-egui/src/panels/tests_links.rs | 18 +++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index af85690e9d..5c95e17bc7 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -344,7 +344,31 @@ fn badge(ui: &Ui, r: egui::Rect, status: &str) { } } -fn status_tip(r: &Value) -> String { +/// The tooltip of row `r`. A row outside the layer tree also names where it is stored +/// (`links.list`'s `owner`): the symbol, graph design or pattern whose art holds it, and the object +/// whose opacity mask holds it, by `mask` (that object's name) or else by its id. +pub(super) fn status_tip(r: &Value, mask: Option) -> String { + let tip = file_tip(r); + let owner = &r["owner"]; + let name = owner["name"].as_str().unwrap_or_default(); + let art = match owner["kind"].as_str() { + Some("symbol") => Some(tl!("Symbols")), + Some("graphDesign") => Some(tl!("Graph Design")), + Some("pattern") => Some(tl!("Pattern")), + _ => None, + }; + let tip = match art { + Some(kind) => format!("{tip}\n{kind}: {name}"), + None => tip, + }; + match owner["maskOf"].as_u64() { + Some(id) => format!("{tip}\n{}: {}", tl!("Opacity Mask"), mask.unwrap_or_else(|| id.to_string())), + None => tip, + } +} + +/// The file, status and notes part of [`status_tip`]. +fn file_tip(r: &Value) -> String { let path = r["found"].as_str().or(r["path"].as_str()).unwrap_or_default(); let tip = match r["status"].as_str().unwrap_or_default() { "missing" => crate::i18n::fmt(tl!("Missing: {path}"), &[("path", path)]), @@ -495,7 +519,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { egui::FontId::proportional(12.5), t.text, ); - let resp = resp.on_hover_text(status_tip(r)); + let mask = r["owner"]["maskOf"] + .as_u64() + .and_then(|m| doc.stored_node(NodeId(m))) + .map(|(n, _)| n) + .map(|n| super::layers::shown_name(app, n, crate::i18n::current())); + let resp = resp.on_hover_text(status_tip(r, mask)); if resp.double_clicked() { clicked = Some((id, egui::Modifiers::NONE, true)); } else if resp.clicked() { diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index be5e17e374..89dfba5f43 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -178,6 +178,24 @@ fn a_link_inside_a_symbol_is_listed_and_picked_in_the_panel() { assert!(selected(&app).is_empty(), "the image in the layers is no longer selected"); } +/// The tooltip of a row outside the layer tree says where the image is stored, so two rows of the +/// same file in different symbols or masks can be told apart. +#[test] +fn a_nested_rows_tooltip_names_what_holds_it() { + let tip = |owner: serde_json::Value, mask: Option<&str>| { + let row = json!({"id": 9, "name": "a.png", "status": "ok", "path": "/x/a.png", "owner": owner}); + super::links::status_tip(&row, mask.map(str::to_string)) + }; + assert_eq!(tip(json!({"kind": "symbol", "name": "Mark"}), None), "/x/a.png\nSymbols: Mark"); + assert_eq!(tip(json!({"kind": "pattern", "name": "Dots"}), None), "/x/a.png\nPattern: Dots"); + assert_eq!(tip(json!({"kind": "graphDesign", "name": "Bar"}), None), "/x/a.png\nGraph Design: Bar"); + assert_eq!(tip(json!({"kind": "layers", "maskOf": 7}), Some("")), "/x/a.png\nOpacity Mask: "); + assert_eq!(tip(json!({"kind": "symbol", "name": "Mark", "maskOf": 7}), None), "/x/a.png\nSymbols: Mark\nOpacity Mask: 7"); + // A row in the layers says only its file. + let row = json!({"id": 9, "name": "a.png", "status": "ok", "path": "/x/a.png"}); + assert_eq!(super::links::status_tip(&row, None), "/x/a.png"); +} + #[test] fn an_empty_document_shows_how_to_add_images() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); From a367065afc0e59511c22bea468292635edfcf5c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 23:26:25 -0800 Subject: [PATCH 06/28] Links: a mask row's tooltip finds its object without walking the stored art The panel collects the objects whose opacity masks hold a listed image in the same pass over the stored art that collects the rows' objects, once per list rebuild. Each frame then finds a row's mask object by the layer tree's index or in that cache, instead of walking every stored root for objects inside symbols, graph designs and patterns. --- crates/ui-egui/src/panels/links.rs | 40 ++++++++++++++---------- crates/ui-egui/src/panels/tests_links.rs | 33 +++++++++++++++++++ 2 files changed, 57 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 5c95e17bc7..2fb130ae3e 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -60,10 +60,18 @@ struct Cache { at: f64, list: Value, info: Option<(u64, Value)>, - /// The objects of the rows outside the layer tree, by id, for their thumbnails. + /// The objects outside the layer tree, by id: those of the rows, for their thumbnails, and + /// those whose opacity masks hold a row's image, for the tooltip. nested: Vec<(u64, std::sync::Arc)>, } +impl Cache { + /// Object `id` outside the layer tree, as [`cached`] collected it. + fn nested_node(&self, id: u64) -> Option<&std::sync::Arc> { + self.nested.binary_search_by_key(&id, |(n, _)| *n).ok().and_then(|i| self.nested.get(i)).map(|(_, n)| n) + } +} + fn options(ctx: &egui::Context) -> Options { pstate(ctx, "links-options") } @@ -86,9 +94,16 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< if stale { c.list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; (c.key, c.at) = (key, now); - // One pass over the stored art for the rows outside the layer tree, not one per frame. - let mut want: std::collections::HashSet = - c.list["links"].as_array().into_iter().flatten().filter(|r| nested_row(r)).filter_map(|r| r["id"].as_u64()).collect(); + // One pass over the stored art for the rows outside the layer tree and the objects whose + // opacity masks hold them, not one per frame. + let mut want: std::collections::HashSet = c.list["links"] + .as_array() + .into_iter() + .flatten() + .filter(|r| nested_row(r)) + .flat_map(|r| [r["id"].as_u64(), r["owner"]["maskOf"].as_u64()]) + .flatten() + .collect(); c.nested.clear(); if !want.is_empty() && let Some(st) = app.session.active() @@ -477,16 +492,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if o.thumb > 0.0 { let tr = egui::Rect::from_min_size(egui::pos2(x, rect.center().y - o.thumb / 2.0), vec2(o.thumb, o.thumb)); ui.painter().rect_filled(tr, 0.0, egui::Color32::WHITE); - let node = if nested_row(r) { - cache - .nested - .binary_search_by_key(&id, |(n, _)| *n) - .ok() - .and_then(|i| cache.nested.get(i)) - .map(|(_, n)| std::sync::Arc::clone(n)) - } else { - super::layers::node_arc(&doc, NodeId(id)) - }; + let node = + if nested_row(r) { cache.nested_node(id).map(std::sync::Arc::clone) } else { super::layers::node_arc(&doc, NodeId(id)) }; if let Some(n) = node { super::layers::real_thumb(ui, &thumbs, &n, tr); } @@ -519,10 +526,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { egui::FontId::proportional(12.5), t.text, ); + // The mask's object by the layer tree's index or from the cache: no walk of the + // stored art each frame. let mask = r["owner"]["maskOf"] .as_u64() - .and_then(|m| doc.stored_node(NodeId(m))) - .map(|(n, _)| n) + .and_then(|m| doc.node(NodeId(m)).or_else(|| cache.nested_node(m).map(|n| &**n))) .map(|n| super::layers::shown_name(app, n, crate::i18n::current())); let resp = resp.on_hover_text(status_tip(r, mask)); if resp.double_clicked() { diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 89dfba5f43..8055c1288c 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -196,6 +196,39 @@ fn a_nested_rows_tooltip_names_what_holds_it() { assert_eq!(super::links::status_tip(&row, None), "/x/a.png"); } +/// The tooltip of an image in the opacity mask of an object inside a symbol names that object, +/// which the panel finds among the objects it collected with the list. +#[test] +fn a_mask_rows_tooltip_names_its_object_inside_a_symbol() { + let dir = Folder::new("mask-owner"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap(); + let mask = dir.file("mask.png", &png(20, 20)); + let mask = app.run("file.place", json!({"path": mask, "at": [40, 40]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("transparency.makeOpacityMask", json!({"ids": [rect, mask]})).unwrap(); + app.run("symbol.new", json!({"name": "Mark", "ids": [rect]})).unwrap(); + app.run("edit.clear", json!({"ids": selected(&app)})).unwrap(); + let list = app.run("links.list", json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == "mask.png").unwrap_or_else(|| panic!("{list}")).clone(); + assert_eq!(row["owner"]["kind"], "symbol", "{list}"); + let owner = vectorcraft_doc::NodeId(row["owner"]["maskOf"].as_u64().unwrap_or_else(|| panic!("{list}"))); + let doc = app.session.active().unwrap().doc.clone(); + assert!(doc.node(owner).is_none(), "the masked object is outside the layer tree"); + let name = super::layers::shown_name(&app, doc.stored_node(owner).unwrap().0, crate::i18n::current()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, events: Vec, time: f64| { + super::tests_appearance::frame_raw(&ctx, app, egui::RawInput { events, time: Some(time), ..Default::default() }, super::links::show) + }; + let at = super::tests_appearance::text_rect(&frame(&mut app, vec![], 1.0), "mask.png").center(); + frame(&mut app, vec![egui::Event::PointerMoved(at)], 2.0); + frame(&mut app, vec![], 4.0); + let text: Vec = frame(&mut app, vec![], 4.1).into_iter().map(|(t, _)| t).collect(); + let want = format!("Opacity Mask: {name}"); + assert!(text.iter().any(|t| t.contains(&want)), "{want} in {text:?}"); +} + #[test] fn an_empty_document_shows_how_to_add_images() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); From 6dcbf804ca60146f14adc789940a0fc24e6c23f9 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Fri, 13 Nov 2026 13:28:16 +0500 Subject: [PATCH 07/28] Character panel: icons for the font height references (#6304) The Set Font Height Reference dropdown shows an icon before each reference's name, in the open list and in the closed field: Em Box frames the whole square around an A, Cap Height and x-Height put a bar from the baseline to the top of a capital A or a lowercase x, and ICF Box frames a square inset in the em square. The icons are painted with egui's painter in the row's text colour and the theme accent. widgets::dropdown_icon_names is a dropdown_names whose options carry a painted icon. --- crates/ui-egui/src/panels/character.rs | 77 +++++++++++++++++++- crates/ui-egui/src/panels/character/tests.rs | 64 ++++++++++++++++ crates/ui-egui/src/widgets.rs | 4 +- crates/ui-egui/src/widgets/dropdowns.rs | 47 +++++++++++- docs/target-app-parity.md | 5 +- 5 files changed, 189 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 2ad678bf62..d1712c42d7 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -940,18 +940,89 @@ const FONT_HEIGHT_REFERENCES: [(vectorcraft_doc::FontHeightReference, &str); 4] (vectorcraft_doc::FontHeightReference::IcfBox, "icfBox"), ]; +/// The size of the icon before each name in the Set Font Height Reference dropdown. +const FONT_HEIGHT_ICON: f32 = 16.0; + /// The Set Font Height Reference dropdown, `width` wide: the height of the font that the Font Size -/// measures, blank where the characters the panel acts on differ. +/// measures, blank where the characters the panel acts on differ. Each reference shows an icon of +/// the height it measures before its name ([`paint_font_height_icon`], #6304). fn font_height_reference(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) { // The labels of [`FONT_HEIGHT_REFERENCES`], in its order. let labels = [tl!("Em Box"), tl!("Cap Height"), tl!("x-Height"), tl!("ICF Box")]; let current = shared(app, |s| s.font_height_reference); - let shown = FONT_HEIGHT_REFERENCES.iter().zip(labels).find(|(r, _)| Some(r.0) == current).map_or("", |(_, l)| l); - if let Some((_, key)) = widgets::dropdown_names(ui, "ch-font-height", shown, &labels, width).and_then(|i| FONT_HEIGHT_REFERENCES.get(i)) { + let shown = FONT_HEIGHT_REFERENCES.iter().position(|(r, _)| Some(*r) == current); + let mark = Tokens::get(ui.ctx()).accent; + let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32| { + if let Some((r, _)) = FONT_HEIGHT_REFERENCES.get(i) { + paint_font_height_icon(ui.painter(), rect, *r, ink, mark); + } + }; + let picked = widgets::dropdown_icon_names(ui, "ch-font-height", shown, &labels, width, FONT_HEIGHT_ICON, icon); + if let Some((_, key)) = picked.and_then(|i| FONT_HEIGHT_REFERENCES.get(i)) { format(app, json!({"fontHeightReference": key})); } } +/// Paints the icon of font height reference `r` into the square `rect` (#6304): a letter drawn in +/// `ink` on a baseline, and in `mark` the height the reference measures. Em Box frames the whole +/// square around an "A"; Cap Height puts a bar from the baseline to the top of a capital "A" +/// beside it; x-Height a bar from the baseline to the top of a lowercase "x"; ICF Box frames a +/// square inset in the faint em square around an ideograph-like cross, as the ideographic +/// character face sits inside the em box. The drawings are VectorCraft's own. +fn paint_font_height_icon( + painter: &egui::Painter, + rect: egui::Rect, + r: vectorcraft_doc::FontHeightReference, + ink: egui::Color32, + mark: egui::Color32, +) { + use vectorcraft_doc::FontHeightReference as R; + // A point at (x, y) in the unit square mapped onto `rect`. + let p = |x: f32, y: f32| rect.lerp_inside(vec2(x, y)); + let glyph = egui::Stroke::new(1.3, ink); + let measure = egui::Stroke::new(1.2, mark); + let line = |a: (f32, f32), b: (f32, f32), stroke: egui::Stroke| painter.line_segment([p(a.0, a.1), p(b.0, b.1)], stroke); + let frame = |min: f32, max: f32, stroke: egui::Stroke| { + painter.rect_stroke(egui::Rect::from_min_max(p(min, min), p(max, max)), 0.0, stroke, egui::StrokeKind::Middle); + }; + // A capital A from `left` to `right`, its apex at `top` and its feet on `base`. + let capital = |left: f32, right: f32, top: f32, base: f32| { + let mid = (left + right) / 2.0; + painter.add(egui::Shape::line(vec![p(left, base), p(mid, top), p(right, base)], glyph)); + let bar = top + (base - top) * 0.62; + let inset = (right - left) * 0.5 * 0.62; + line((mid - inset, bar), (mid + inset, bar), glyph); + }; + // A vertical measure from `top` to `base` at `x`, with ticks at its ends. + let height_bar = |x: f32, top: f32, base: f32| { + line((x, top), (x, base), measure); + line((x - 0.1, top), (x + 0.1, top), measure); + line((x - 0.1, base), (x + 0.1, base), measure); + }; + let (base, cap_top, x_top) = (0.86, 0.16, 0.46); + match r { + R::EmBox => { + frame(0.06, 0.94, measure); + capital(0.26, 0.74, 0.26, 0.76); + } + R::CapHeight => { + capital(0.06, 0.6, cap_top, base); + height_bar(0.82, cap_top, base); + } + R::XHeight => { + line((0.1, x_top), (0.54, base), glyph); + line((0.54, x_top), (0.1, base), glyph); + height_bar(0.82, x_top, base); + } + R::IcfBox => { + frame(0.06, 0.94, egui::Stroke::new(1.0, ink.gamma_multiply(0.4))); + frame(0.2, 0.8, measure); + line((0.33, 0.5), (0.67, 0.5), glyph); + line((0.5, 0.31), (0.5, 0.69), glyph); + } + } +} + /// The font family menu and the font style dropdown of style `s` (Character and Properties panels, /// Control bar), with their `ids` and `widths`. The mouse wheel over the closed family field steps /// the text through the families. diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index a90286e2fb..4e403f0903 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -822,6 +822,70 @@ fn show_font_height_options_shows_the_font_height_reference() { assert!(item(&texts(&ctx, &mut app, show), "Cap Height").is_none()); } +/// The Set Font Height Reference dropdown shows an icon before each reference's name, in the +/// closed field and in the open list, and each reference's icon is its own (#6304). +#[test] +fn font_height_references_show_their_icons() { + use super::super::tests_appearance::click; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 12})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, FONT_HEIGHT_OPTIONS, true); + // Every text drawn with its rect, and the rects of every other shape drawn. + let frame = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, marks: &mut Vec) { + match s { + egui::Shape::Text(t) => texts.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, marks)), + egui::Shape::Noop => {} + s => marks.push(s.visual_bounding_rect()), + } + } + let (mut texts, mut marks) = (vec![], vec![]); + for c in &out.shapes { + collect(&c.shape, &mut texts, &mut marks); + } + (texts, marks) + }; + // The shapes in the icon's place before the text `rect`, relative to that place and rounded. + let icon = |marks: &[egui::Rect], rect: egui::Rect| { + let place = egui::Rect::from_min_max( + egui::pos2(rect.min.x - FONT_HEIGHT_ICON - 8.0, rect.center().y - 10.0), + egui::pos2(rect.min.x, rect.center().y + 10.0), + ); + let mut found: Vec<[i32; 4]> = marks + .iter() + .filter(|m| m.is_finite() && place.contains_rect(**m)) + .map(|m| [m.min.x - place.min.x, m.min.y - place.min.y, m.max.x - place.min.x, m.max.y - place.min.y].map(|v| v.round() as i32)) + .collect(); + found.sort_unstable(); + found + }; + frame(&ctx, &mut app); + let (texts, marks) = frame(&ctx, &mut app); + let field = texts.iter().find(|(t, _)| t == "Em Box").map(|(_, r)| *r).expect("the closed field shows Em Box"); + assert!(icon(&marks, field).len() >= 2, "no icon before Em Box in the closed field: {:?}", icon(&marks, field)); + click(&ctx, &mut app, field.center(), show); + frame(&ctx, &mut app); + let (texts, marks) = frame(&ctx, &mut app); + let mut icons = vec![]; + for name in ["Em Box", "Cap Height", "x-Height", "ICF Box"] { + // The list's row is the last text of that name drawn (the closed field is drawn first). + let row = texts.iter().rev().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("the open list shows {name}: {texts:?}")); + let found = icon(&marks, row); + assert!(found.len() >= 2, "no icon before {name} in the open list: {found:?}"); + icons.push(found); + } + for (i, a) in icons.iter().enumerate() { + assert!(icons.iter().skip(i + 1).all(|b| a != b), "two references share an icon: {icons:?}"); + } +} + /// Tate-chu-yoko is in the panel menu with the East Asian options, and choosing it marks the /// selected characters. #[test] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 826e7e02f6..52849bc2bc 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -47,8 +47,8 @@ pub use drag::{ use dropdowns::combo_button_id; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named, field_focused_in, popover_is_open}; pub use dropdowns::{ - dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, - panel_scroll, popover, set_menu_floor, strip_scroll, + dropdown, dropdown_icon_names, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, + menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, }; #[cfg(test)] pub(crate) use dropdowns::{menu_floor, menu_room_either}; diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 44903d6613..c8fba54aed 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -1,3 +1,5 @@ +use egui::IntoAtoms as _; + use super::drag::PanelDrag; use super::labels::{PreviousLabel, label_field, name_field, take_previous_label}; use super::text::take_armed_focus; @@ -33,6 +35,37 @@ pub fn dropdown_names_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option< }) } +/// [`dropdown_names`] whose options each show an icon before their name, in the open list and in +/// the closed field, so that a name that says little on its own is shown with a picture of what it +/// means (#6304). `icon(ui, rect, index, ink)` paints option `index`'s icon into `rect`, an +/// `icon_size` square, with `ink`, the colour the row's name is drawn in. `current` is the option +/// shown; `None` shows a blank field (characters that differ). +pub fn dropdown_icon_names( + ui: &mut Ui, + id: impl std::hash::Hash, + current: Option, + options: &[&str], + width: f32, + icon_size: f32, + icon: impl Fn(&Ui, Rect, usize, egui::Color32), +) -> Option { + let icon = &icon; + let atom = move |i: usize| egui::Atom::paint(Vec2::splat(icon_size), move |ui, a| icon(ui, a.rect, i, a.fallback_text_color)); + let shown = match current.and_then(|i| options.get(i).map(|name| (i, *name))) { + Some((i, name)) => (atom(i), egui::RichText::new(name).size(12.0)).into_atoms(), + None => egui::RichText::new("").size(12.0).into_atoms(), + }; + combo_atoms_named(ui, id, None, shown, width, |ui| { + let mut chosen = None; + for (i, o) in options.iter().enumerate() { + if ui.add(egui::Button::selectable(current == Some(i), (atom(i), *o))).clicked() { + chosen = Some(i); + } + } + chosen + }) +} + /// [`dropdown`] whose options can be disabled (`enabled(index)`: greyed and not choosable). pub fn dropdown_with( ui: &mut Ui, @@ -88,6 +121,18 @@ pub(crate) fn combo_named( current: &str, width: f32, list: impl FnOnce(&mut Ui) -> Option, +) -> Option { + combo_atoms_named(ui, id, name, egui::RichText::new(current).size(12.0), width, list) +} + +/// [`combo_named`] whose closed field shows the atoms `current` (an icon and a name, say). +fn combo_atoms_named<'a, R>( + ui: &mut Ui, + id: impl std::hash::Hash, + name: Option<&str>, + current: impl egui::IntoAtoms<'a>, + width: f32, + list: impl FnOnce(&mut Ui) -> Option, ) -> Option { let t = Tokens::get(ui.ctx()); let label = take_previous_label(ui); @@ -99,7 +144,7 @@ pub(crate) fn combo_named( let button_id = combo_button_id(ui, &id); let enter_for_combo = ui.memory(|m| m.has_focus(button_id)) || craft_ui::ComboBox::is_open(ui.ctx(), button_id); let response = craft_ui::ComboBox::from_id_salt(HashOnly(&id)) - .selected_text(egui::RichText::new(current).size(12.0)) + .selected_text(current) .width(width - 4.0) .height(ui.spacing().combo_height) .show_ui(ui, list); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 086d4cfc0d..7904896324 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -1224,7 +1224,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). - The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). + The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. The Character panel's Anti-aliasing Method dropdown, under Character Rotation, sets how the edges of the selected type objects are drawn as pixels (`text.setFormat {antiAlias}`), for the whole object, with each frame of a thread keeping its own method and graph labels keeping it when the graph is drawn again, on the canvas, in raster exports and when the type is rasterized. VectorCraft defines the methods: Sharp, the default, draws edges as before; None paints a pixel only where the type covers at least half of it; Crisp shows a pixel covered by a share c at `2c - 0.5`, and Strong shows it at `2c`, each kept between 0 and 1. SVG, PDF and EPS export are unchanged. Scores and hours unchanged. @@ -2168,6 +2168,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Character panel: the Set Font Height Reference dropdown shows an icon of the height each reference measures before its name, in the open list and in the closed field (#6304). Scores and estimates unchanged. | | 2026-11-12 | minor | Object › Rasterize with the Grayscale colour model makes a grayscale image (one gray channel, with alpha over a transparent background), so the Properties panel says Grayscale and a fill color colorizes it; Bitmap makes a 1-bit image (a TIFF), or a black-and-white gray image with alpha over a transparent background, since 1-bit gray with alpha is no format readers take. Both were RGB images of gray pixels (#6969). Scores and estimates unchanged. | | 2026-11-12 | minor | `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints (its strokes' miter tips, and strokes a Transform effect moves, included), after its glyphs grown by half its strokes' weight; `.ai` import evidence updated (#6824); scores and estimates unchanged. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | From eee96556e629b7fc01b0672b606882e34ede77d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 01:09:38 -0800 Subject: [PATCH 08/28] Simplify: a refitted curve becomes a line only when its joins stay smooth Simplify, Object > Path > Smooth, the Smooth tool and freehand strokes turned every refitted curve whose handles lay near its chord into a straight line. A short curve whose end directions were off the chord passed that test, and the anchor between it and the next curve became a corner the path did not have: a Smooth tool drag along a line jagged by up to 6 pt left corners of 7.7 to 40.6 degrees. A curve now becomes a line only when the line runs within 0.5 degrees of the directions the path arrives and leaves along. A nearly straight piece that would turn more stays a flat curve. Convert to Straight Lines is unchanged. --- crates/engine/src/tests/draw2.rs | 31 ++++++++++++++++++++++ crates/pathops/src/edit.rs | 25 +++++++++++++++--- crates/pathops/tests/it/ops.rs | 45 ++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 99 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 5986b618fd..d365fc83a8 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1367,6 +1367,37 @@ fn smooth_tool_reduces_jagged_path() { assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0)); } +/// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and +/// a line: every anchor between the path's ends turns by at most 1°. +#[test] +fn smooth_tool_leaves_no_corner_where_a_curve_meets_a_line() { + let mut s = session(); + let mut seed = 7u64; + let anchors: Vec<_> = (0..=60) + .map(|i| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0; + json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise}) + }) + .collect(); + let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let drag_points: Vec<(f64, f64)> = (0..=64).map(|i| (90.0 + f64::from(i) * 5.0, 200.0)).collect(); + drag(&mut s, "smooth", &drag_points, Mods::default()); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert!(sp.anchors.len() < 61, "the path is smoothed: {}", sp.anchors.len()); + let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord); + for i in 1..sp.segment_count() { + let (prev, next) = (sp.segment(i - 1), sp.segment(i)); + let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0); + let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0); + let turn = arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees(); + let kinds = (sp.segment_is_line(i - 1), sp.segment_is_line(i)); + assert!(turn <= 1.0, "anchor {i} turns {turn}° (lines before and after: {kinds:?}): {:?}", sp.anchors[i]); + } +} + /// #1512: a short drag over a small bump smooths the stretch of path under it. The long straight /// sides next to the bump stay straight lines from their far ends, which keep their place. #[test] diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index d8d121ecb9..19089dfd2e 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -328,14 +328,33 @@ fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, ends: Op } // The fit may be `tol * 0.98` from the lines between the samples, those lines may be // `SAMPLE_GAP` of `tol` from the path, and the curve the test below turns into a line moves by up - // to 1.5% of `tol`: 3/4 of how far its handles may be from the line. + // to 1.5% of `tol`: 3/4 of how far its handles may be from the line. The fitted curves join + // smoothly, so a curve becomes a line only when the line keeps both of its joins smooth. let (t0, t1) = ends.map_or((start_tangent(&first.c), end_tangent(&last.c)), |d| (d, d)); - for c in fit_cubics(&pts, t0, t1, tol * 0.98) { - let line = is_straight(&c, tol * 0.02); + let fitted = fit_cubics(&pts, t0, t1, tol * 0.98); + let mut arrive = t0; + for (k, &c) in fitted.iter().enumerate() { + let leave = fitted.get(k + 1).map_or(t1, start_tangent); + let line = is_straight(&c, tol * 0.02) && line_keeps_joins(&c, arrive, leave); + arrive = if line { unit(c.p3 - c.p0).unwrap_or(arrive) } else { end_tangent(&c) }; result.push(if line { Seg::line(c.p0, c.p3) } else { Seg { c, line } }); } } +/// Most degrees between the line from a refitted curve's start to its end and the directions the +/// path arrives and leaves along, for the curve to become that line: so every join next to such a +/// line turns by at most this much. VectorCraft's own value. +const LINE_JOIN_DEG: f64 = 0.5; + +/// Whether the line from `c.p0` to `c.p3` is within [`LINE_JOIN_DEG`] of `arrive`, the direction the +/// path arrives at `c.p0` along, and of `leave`, the direction it leaves `c.p3` along. A curve whose +/// ends are at one point, or a direction of no length, gives `false`. +fn line_keeps_joins(c: &CubicBez, arrive: Vec2, leave: Vec2) -> bool { + let (Some(dir), Some(arrive), Some(leave)) = (unit(c.p3 - c.p0), unit(arrive), unit(leave)) else { return false }; + let min = LINE_JOIN_DEG.to_radians().cos(); + dir.dot(arrive) >= min && dir.dot(leave) >= min +} + /// `pts` (a run's samples, in order) smoothed along the path: each point becomes the Gaussian-weighted /// mean of the points around it, `sigma` points of arc length wide, the window narrowing towards the /// ends so that the first and last points stay where they are. Consecutive samples within diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 492aaf56f1..d48e1c5dd8 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -417,6 +417,51 @@ fn simplify_keeps_square_corners() { assert!(!has_curves(&s)); } +/// The largest turn, in degrees, at an anchor of `sp` that is not an end of an open subpath: the +/// angle between the direction a segment arrives along and the one the next leaves along. +fn largest_join_turn(sp: &SubPath) -> f64 { + let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord); + let n = sp.segment_count(); + let first = usize::from(!sp.closed); + (first..n) + .map(|i| { + let (prev, next) = (sp.segment((i + n - 1) % n), sp.segment(i)); + let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0); + let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0); + arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees() + }) + .fold(0.0, f64::max) +} + +/// A refitted curve becomes a line only when the line keeps the smooth joins on both sides of it: +/// with no corners kept, the refit of a jagged line or of an arc running into a line turns by at most +/// 0.5° at every anchor. Points that all lie on one line still become one line. +#[test] +fn simplify_turns_a_curve_into_a_line_only_where_the_joins_stay_smooth() { + let mut seed = 7u64; + let mut noise = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0 + }; + let jagged: Vec = (0..=60).map(|i| Point::new(100.0 + f64::from(i) * 5.0, 200.0 + 6.0 * noise())).collect(); + let mut arc_into_line: Vec = + (0..=40).map(|i| Point::new(50.0 * (f64::from(i) / 80.0 * PI).cos(), 50.0 * (f64::from(i) / 80.0 * PI).sin())).collect(); + arc_into_line.extend((1..=20).map(|i| Point::new(-f64::from(i) * 2.0, 50.0))); + for pts in [&jagged, &arc_into_line] { + let path = PathData::single(SubPath::polyline(pts, false)); + for tolerance in [1.0, 2.5, 5.0] { + let s = simplify_with(&path, &SimplifyOptions { tolerance, corner_angle_deg: 179.0, ..Default::default() }); + let turn = largest_join_turn(&s.subpaths[0]); + assert!(turn <= 0.5 + 1e-9, "{tolerance} pt: an anchor turns {turn}°: {s:?}"); + assert!(max_deviation(&path, &s) <= tolerance + 1e-6, "{tolerance} pt: {}", max_deviation(&path, &s)); + } + } + let in_line: Vec = [0.0, 3.0, 10.0, 11.0, 40.0, 41.5, 90.0, 100.0].map(|x| Point::new(x, 0.5 * x)).to_vec(); + let s = simplify_with(&PathData::single(SubPath::polyline(&in_line, false)), &SimplifyOptions { tolerance: 1.0, ..Default::default() }); + assert_eq!(s.anchor_count(), 2, "{s:?}"); + assert!(!has_curves(&s), "{s:?}"); +} + #[test] fn simplify_straight_lines_option() { let c = dense_circle(50.0, 200); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 086d4cfc0d..1ae705ab40 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1204,6 +1204,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Nearly unchanged appearance is expected when reducing points. The checklist is partial, without raising scores. Simplify and Add Anchor Points record no undo step when they change no path, and a path they leave as it is keeps its live shape. Simplify keeps its result within the tolerance of the path, on long arcs and on paths of many anchors alike (`fit.rs` tests `no_fitted_piece_is_farther_than_the_tolerance` and `long_arcs_stay_within_the_tolerance`). A closed subpath that refits to one curve is dropped, so this does not hold for it. A segment that would need more than 65,536 samples at that tolerance stays as it is, and with Convert to Straight Lines it becomes evenly spaced lines instead, up to 65,536, which past the limits in `docs/mcp.md` (Simplify) can be farther than the tolerance from the segment. + Simplify, Object › Path › Smooth, the Smooth tool and freehand strokes (`path.freehand`) turn a refitted curve into a straight line only when the line runs within 0.5° of the directions the path arrives and leaves along, so no corner appears where a curve meets a line; a nearly straight piece that would turn more stays a flat curve (`ops.rs` test `simplify_turns_a_curve_into_a_line_only_where_the_joins_stay_smooth`). The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. From b219decd755d7fb3c8ddafbb4bd2ea118d99fc7c Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Fri, 13 Nov 2026 14:19:58 +0500 Subject: [PATCH 09/28] Character panel: the highlighted font height icon keeps its contrast (#6304) On the open list's row of the current reference, drawn on the accent-tinted selection fill, the icon draws its measure in the name's colour instead of the accent, which lost its contrast there. The other rows and the closed field keep the accent. --- crates/ui-egui/src/panels/character.rs | 7 ++- crates/ui-egui/src/panels/character/tests.rs | 65 ++++++++++++++++++++ crates/ui-egui/src/widgets/dropdowns.rs | 19 +++--- 3 files changed, 82 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index d1712c42d7..b761e6fd66 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -951,8 +951,11 @@ fn font_height_reference(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) { let labels = [tl!("Em Box"), tl!("Cap Height"), tl!("x-Height"), tl!("ICF Box")]; let current = shared(app, |s| s.font_height_reference); let shown = FONT_HEIGHT_REFERENCES.iter().position(|(r, _)| Some(*r) == current); - let mark = Tokens::get(ui.ctx()).accent; - let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32| { + let accent = Tokens::get(ui.ctx()).accent; + let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, highlighted: bool| { + // On the highlighted row the selection fill is accent-tinted, so the measure takes the + // name's colour there to keep its contrast. + let mark = if highlighted { ink } else { accent }; if let Some((r, _)) = FONT_HEIGHT_REFERENCES.get(i) { paint_font_height_icon(ui.painter(), rect, *r, ink, mark); } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 4e403f0903..dd4b12adf5 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -886,6 +886,71 @@ fn font_height_references_show_their_icons() { } } +/// In the open Set Font Height Reference list, the current reference's row is drawn on the +/// accent-tinted selection fill, so its icon draws the measure in the name's colour rather than +/// the accent, which would lose its contrast there; the other rows keep the accent (#6304). +#[test] +fn the_highlighted_font_height_icon_keeps_its_contrast() { + use super::super::tests_appearance::click; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Hx", "size": 12})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, FONT_HEIGHT_OPTIONS, true); + let accent = Tokens::get(&ctx).accent; + // Every text drawn with its rect, and every stroke drawn with its rect and colour. + let frame = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, strokes: &mut Vec<(egui::Rect, egui::Color32)>) { + match s { + egui::Shape::Text(t) => texts.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, strokes)), + egui::Shape::LineSegment { stroke, .. } => strokes.push((s.visual_bounding_rect(), stroke.color)), + egui::Shape::Path(p) => { + if let egui::epaint::ColorMode::Solid(c) = p.stroke.color { + strokes.push((s.visual_bounding_rect(), c)); + } + } + egui::Shape::Rect(r) => strokes.push((s.visual_bounding_rect(), r.stroke.color)), + _ => {} + } + } + let (mut texts, mut strokes) = (vec![], vec![]); + for c in &out.shapes { + collect(&c.shape, &mut texts, &mut strokes); + } + (texts, strokes) + }; + // The stroke colours in the icon's place before the text `rect`. + let colours = |strokes: &[(egui::Rect, egui::Color32)], rect: egui::Rect| -> Vec { + let place = egui::Rect::from_min_max( + egui::pos2(rect.min.x - FONT_HEIGHT_ICON - 8.0, rect.center().y - 10.0), + egui::pos2(rect.min.x, rect.center().y + 10.0), + ); + strokes.iter().filter(|(r, _)| r.is_finite() && place.contains_rect(*r)).map(|(_, c)| *c).collect() + }; + frame(&ctx, &mut app); + let (texts, _) = frame(&ctx, &mut app); + let field = texts.iter().find(|(t, _)| t == "Em Box").map(|(_, r)| *r).expect("the closed field shows Em Box"); + click(&ctx, &mut app, field.center(), show); + frame(&ctx, &mut app); + let (texts, strokes) = frame(&ctx, &mut app); + let row = |name: &str| texts.iter().rev().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("the open list shows {name}")); + // The list fades in, so colours are compared without their alpha. + let rgb = |c: egui::Color32| { + let [r, g, b, _] = c.to_srgba_unmultiplied(); + [r, g, b] + }; + let is_accent = |c: &egui::Color32| rgb(*c).iter().zip(rgb(accent)).all(|(a, b)| a.abs_diff(b) <= 4); + let current = colours(&strokes, row("Em Box")); + assert!(!current.is_empty() && !current.iter().any(is_accent), "the highlighted Em Box icon draws in the accent: {current:?}"); + let other = colours(&strokes, row("Cap Height")); + assert!(other.iter().any(is_accent), "the other rows keep the accent measure: {other:?}"); +} + /// Tate-chu-yoko is in the panel menu with the East Asian options, and choosing it marks the /// selected characters. #[test] diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index c8fba54aed..a2741ff1cb 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -37,9 +37,11 @@ pub fn dropdown_names_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option< /// [`dropdown_names`] whose options each show an icon before their name, in the open list and in /// the closed field, so that a name that says little on its own is shown with a picture of what it -/// means (#6304). `icon(ui, rect, index, ink)` paints option `index`'s icon into `rect`, an -/// `icon_size` square, with `ink`, the colour the row's name is drawn in. `current` is the option -/// shown; `None` shows a blank field (characters that differ). +/// means (#6304). `icon(ui, rect, index, ink, highlighted)` paints option `index`'s icon into +/// `rect`, an `icon_size` square, with `ink`, the colour the row's name is drawn in; +/// `highlighted` is true on the open list's row of the current option, drawn on the selection +/// fill, where an accent-coloured mark would lose its contrast. `current` is the option shown; +/// `None` shows a blank field (characters that differ). pub fn dropdown_icon_names( ui: &mut Ui, id: impl std::hash::Hash, @@ -47,18 +49,21 @@ pub fn dropdown_icon_names( options: &[&str], width: f32, icon_size: f32, - icon: impl Fn(&Ui, Rect, usize, egui::Color32), + icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), ) -> Option { let icon = &icon; - let atom = move |i: usize| egui::Atom::paint(Vec2::splat(icon_size), move |ui, a| icon(ui, a.rect, i, a.fallback_text_color)); + let atom = move |i: usize, highlighted: bool| { + egui::Atom::paint(Vec2::splat(icon_size), move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)) + }; let shown = match current.and_then(|i| options.get(i).map(|name| (i, *name))) { - Some((i, name)) => (atom(i), egui::RichText::new(name).size(12.0)).into_atoms(), + Some((i, name)) => (atom(i, false), egui::RichText::new(name).size(12.0)).into_atoms(), None => egui::RichText::new("").size(12.0).into_atoms(), }; combo_atoms_named(ui, id, None, shown, width, |ui| { let mut chosen = None; for (i, o) in options.iter().enumerate() { - if ui.add(egui::Button::selectable(current == Some(i), (atom(i), *o))).clicked() { + let on = current == Some(i); + if ui.add(egui::Button::selectable(on, (atom(i, on), *o))).clicked() { chosen = Some(i); } } From f81793d671b703d74f07376827f39bb58c91b9fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 01:22:51 -0800 Subject: [PATCH 10/28] View: Pixel Snapping Options choose whether Snap to Pixel snaps drawing, moving and scaling Control bar > Snapping > Pixel Snapping Options... opens a dialog with three checkboxes: Snap to Pixel While Drawing, While Moving and While Scaling. OK sets them; Cancel leaves them as they were. While View > Snap to Pixel is off, the dialog notes that the options take effect once it is on. - view.snapToPixel.options {drawing?, moving?, scaling?} reads and sets them. They are kept in the preferences as the pixelSnap group, all on by default, so turning Snap to Pixel on behaves as before. An unknown key or a value that is not a boolean is refused and changes nothing. The command has a parameter schema, which raises the API level to 4. - Drawing covers points the drawing tools place, the Knife's straight cut, the Measure tool and the rulers' origin. Moving covers Selection and Direct Selection moves, ruler guides, artboard moves and the Rotate, Reflect and Shear tools' drags. Scaling covers bounding-box, Free Transform, artboard and slice handles and the Scale tool's drag. An edit whose option is off snaps as it does with Snap to Pixel off. - Align New Objects to Pixel Grid and the objects' pixel-aligned property do not depend on these options. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/prefscmds.rs | 14 ++-- crates/engine/src/cmd/views.rs | 36 ++++++++- crates/engine/src/prefs.rs | 4 + crates/engine/src/schemas.rs | 13 +++- crates/engine/src/tests.rs | 32 ++++++++ crates/engine/src/tests/prefs.rs | 30 ++++++++ crates/engine/src/tooling.rs | 4 +- crates/mcp/src/ui_catalog.rs | 7 +- crates/tools/src/context.rs | 62 ++++++++++++++- crates/tools/src/direct.rs | 14 ++-- crates/tools/src/direct/tests.rs | 27 +++++++ crates/tools/src/draw2/gesture.rs | 6 +- crates/tools/src/guides/snap.rs | 46 ++++++++--- crates/tools/src/guides/targets.rs | 8 +- crates/tools/src/lib.rs | 3 +- crates/tools/src/rulerguide.rs | 9 ++- crates/tools/src/rulerguide/tests.rs | 18 +++++ crates/tools/src/select.rs | 13 ++-- crates/tools/src/select/tests.rs | 45 +++++++++++ crates/tools/src/shape.rs | 2 +- crates/tools/src/slice.rs | 2 +- crates/tools/src/xform/artboard.rs | 16 ++-- crates/tools/src/xform/free.rs | 2 +- crates/tools/src/xform/measure.rs | 2 +- crates/tools/src/xform/transform.rs | 7 +- crates/ui-egui/src/chrome/control_bar.rs | 7 +- crates/ui-egui/src/chrome/tests.rs | 76 +++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 2 + .../ui-egui/src/dialogs/pixel_snap_options.rs | 46 +++++++++++ crates/ui-egui/src/i18n/bg.tsv | 7 ++ crates/ui-egui/src/i18n/bs.tsv | 6 ++ crates/ui-egui/src/i18n/ca.tsv | 7 ++ crates/ui-egui/src/i18n/cs.tsv | 7 ++ crates/ui-egui/src/i18n/da.tsv | 7 ++ crates/ui-egui/src/i18n/de.tsv | 7 ++ crates/ui-egui/src/i18n/el.tsv | 7 ++ crates/ui-egui/src/i18n/es.tsv | 7 ++ crates/ui-egui/src/i18n/fi.tsv | 7 ++ crates/ui-egui/src/i18n/fr.tsv | 7 ++ crates/ui-egui/src/i18n/hi.tsv | 6 ++ crates/ui-egui/src/i18n/hu.tsv | 7 ++ crates/ui-egui/src/i18n/id.tsv | 7 ++ crates/ui-egui/src/i18n/it.tsv | 7 ++ crates/ui-egui/src/i18n/ja.tsv | 7 ++ crates/ui-egui/src/i18n/ka.tsv | 7 ++ crates/ui-egui/src/i18n/ko.tsv | 7 ++ crates/ui-egui/src/i18n/nl.tsv | 7 ++ crates/ui-egui/src/i18n/pl.tsv | 7 ++ crates/ui-egui/src/i18n/pt-br.tsv | 7 ++ crates/ui-egui/src/i18n/ru.tsv | 7 ++ crates/ui-egui/src/i18n/sv.tsv | 7 ++ crates/ui-egui/src/i18n/tr.tsv | 7 ++ crates/ui-egui/src/i18n/uk.tsv | 7 ++ crates/ui-egui/src/i18n/vi.tsv | 7 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 7 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 7 ++ crates/ui-egui/src/menus/invoke.rs | 7 +- crates/ui-egui/src/menus/ui_commands.rs | 7 +- docs/mcp.md | 28 +++++-- docs/target-app-parity.md | 1 + 60 files changed, 714 insertions(+), 69 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/pixel_snap_options.rs diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index a73485f4fa..748e0a125a 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -454,10 +454,10 @@ pub fn spec(key: &str) -> Option<&'static PrefSpec> { /// Preferences kept as one object with a command of their own instead of [`PREF_SPECS`] rows (they /// aren't in the Preferences dialog): the Eyedropper Options (`eyedropper.setOptions`), the /// Perspective Grid Options (`perspective.widget.options`), the Pathfinder Options -/// (`object.pathfinder.options`) and the Snap to Glyph options (`view.snapToGlyph.options`). -/// `prefs.get` and `prefs.set` take them by key (a partial object updates what it names) and -/// `prefs.reset` without a category resets them. -pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap"]; +/// (`object.pathfinder.options`), the Snap to Glyph options (`view.snapToGlyph.options`) and the +/// Pixel Snapping Options (`view.snapToPixel.options`). `prefs.get` and `prefs.set` take them by key +/// (a partial object updates what it names) and `prefs.reset` without a category resets them. +pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap", "pixelSnap"]; /// Validate a value for preference group `key` against `current`. fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result { @@ -477,6 +477,10 @@ fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result< let cur: vectorcraft_tools::GlyphSnap = serde_json::from_value(current.clone()).unwrap_or_default(); cur.merged(v).map(|o| json!(o)) } + "pixelSnap" => { + let cur: vectorcraft_tools::PixelSnap = serde_json::from_value(current.clone()).unwrap_or_default(); + cur.merged(v).map(|o| json!(o)) + } "perspectiveWidget" => { let mut merged = current.clone(); if let (Some(o), Some(p)) = (merged.as_object_mut(), v.as_object()) { @@ -788,7 +792,7 @@ pub fn specs() -> Vec { "Export Preferences", [], None, - "{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder and glyphSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}", + "{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}", always, export ), diff --git a/crates/engine/src/cmd/views.rs b/crates/engine/src/cmd/views.rs index 560da3942c..6e26e9a9e6 100644 --- a/crates/engine/src/cmd/views.rs +++ b/crates/engine/src/cmd/views.rs @@ -1,5 +1,6 @@ //! View → New View… / Edit Views…: saved views stored in the document; per-document view -//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options. +//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options; the Pixel +//! Snapping Options. use serde_json::{Value, json}; use vectorcraft_apischema::{Bound, Param, ParamSchema, Type, Writes}; @@ -72,6 +73,18 @@ static GLYPH_SNAP: ParamSchema = ParamSchema::new( .returns("the options") .writes(Writes::Preferences); +static PIXEL_SNAP: ParamSchema = ParamSchema::new( + &[ + Param::new("drawing", Type::Boolean).optional(), + Param::new("moving", Type::Boolean).optional(), + Param::new("scaling", Type::Boolean).optional(), + ], + "the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them", +) +.returns("the options") +.writes(Writes::Preferences) +.since(4); + pub fn specs() -> Vec { vec![ cmd!( @@ -125,6 +138,16 @@ pub fn specs() -> Vec { glyph_snap_options, schema: &GLYPH_SNAP ), + cmd!( + query "view.snapToPixel.options", + "Pixel Snapping Options", + [], + None, + "{drawing?: bool, moving?: bool, scaling?: bool} the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them → the options", + always, + pixel_snap_options, + schema: &PIXEL_SNAP + ), ] } @@ -133,6 +156,11 @@ fn glyph_snap_options(s: &mut Session, p: &Value) -> Result { Ok(json!(s.prefs.glyph_snap)) } +fn pixel_snap_options(s: &mut Session, p: &Value) -> Result { + s.prefs.pixel_snap = s.prefs.pixel_snap.merged(p).map_err(|e| bad("view.snapToPixel.options", e))?; + Ok(json!(s.prefs.pixel_snap)) +} + fn caps_lock(s: &mut Session, p: &Value) -> Result { if let Some(on) = p.get("on") { s.caps_lock = on.as_bool().ok_or_else(|| bad("view.capsLock", "on must be true or false"))?; @@ -379,15 +407,17 @@ mod tests { ("view.saved.list", json!({"all": true}), "`all`"), ("view.transparencyGrid", json!({"on": 1}), "`on`"), ("view.snapToGlyph.options", json!({"bounds": "off"}), "`bounds`"), + ("view.snapToPixel.options", json!({"moving": "off"}), "`moving`"), + ("view.snapToPixel.options", json!({"drawing": false, "rotating": false}), "`rotating`"), ] { let st = s.doc().unwrap(); let doc = (st.doc.views.clone(), st.history.undo.len(), st.is_dirty()); - let (grid, caps, snap) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap); + let (grid, caps, snap, pixel) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap); let e = s.execute(id, ¶ms).unwrap_err().to_string(); assert!(e.contains(id) && e.contains(named), "{id} {params}: {e}"); let st = s.doc().unwrap(); assert_eq!((&st.doc.views, st.history.undo.len(), st.is_dirty()), (&doc.0, doc.1, doc.2), "{id} {params}"); - assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap), (grid, caps, snap), "{id} {params}"); + assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap), (grid, caps, snap, pixel), "{id} {params}"); } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 05ef5e84f5..98813e999f 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -260,6 +260,9 @@ pub struct Prefs { /// Character panel › Show Snap to Glyph Options: which guides View › Snap to Glyph gives /// (`view.snapToGlyph.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]). pub glyph_snap: vectorcraft_tools::GlyphSnap, + /// Pixel Snapping Options: whether View › Snap to Pixel snaps drawing, moving and scaling + /// (`view.snapToPixel.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]). + pub pixel_snap: vectorcraft_tools::PixelSnap, /// Edit → Transparency Flattener Presets: the user's presets (the built-in ones aren't stored). /// Not a `prefs.set` key or group (resetting the preferences keeps them): `flattener.presets.*` /// edit it. @@ -523,6 +526,7 @@ impl Default for Prefs { eyedropper: Default::default(), pathfinder: Default::default(), glyph_snap: Default::default(), + pixel_snap: Default::default(), flattener_presets: vec![], trace_presets: vec![], gradient_presets: vec![], diff --git a/crates/engine/src/schemas.rs b/crates/engine/src/schemas.rs index 08bc0f719d..8be87b5ab8 100644 --- a/crates/engine/src/schemas.rs +++ b/crates/engine/src/schemas.rs @@ -26,10 +26,11 @@ use crate::cmd::{CommandSpec, bad, command_specs}; use crate::{EngineError, Result}; /// The API level of the commands' parameters. -pub const API_VERSION: u32 = 3; +pub const API_VERSION: u32 = 4; /// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s. -pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a)]; +pub const SCHEMA_HASHES: &[(u32, u64)] = + &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a), (4, 0x1be4_be72_fe16_54c4)]; /// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]). pub fn schema_hash() -> u64 { @@ -311,12 +312,17 @@ mod tests { ("view.transparencyGrid", json!({"on": 1})), ("view.snapToGlyph.options", json!({"bounds": false, "angular": true})), ("view.snapToGlyph.options", json!({"bounds": null})), + ("view.snapToPixel.options", json!({"drawing": false, "scaling": true})), + ("view.snapToPixel.options", json!({"moving": null})), + ("view.snapToPixel.options", json!({"moving": "off"})), + ("view.snapToPixel.options", json!({"rotating": false})), ("view.capsLock", json!(null)), ("view.saved.new", json!(null)), ("view.saved.edit", json!(null)), ("view.saved.list", json!(null)), ("view.transparencyGrid", json!(null)), ("view.snapToGlyph.options", json!(null)), + ("view.snapToPixel.options", json!(null)), ("view.capsLock", json!([])), ("view.saved.new", json!(5)), ("view.transparencyGrid", json!("on")), @@ -325,7 +331,7 @@ mod tests { ("engine.apiReference", json!({"prefix": "view."})), ("engine.apiReference", json!([])), ]; - assert_eq!(schemas().len(), 7); + assert_eq!(schemas().len(), 8); for (id, schema) in schemas() { let written = schema.to_json(); check_schema(&written, id).unwrap_or_else(|e| panic!("{e}\n{written:#}")); @@ -423,6 +429,7 @@ mod tests { ("view.saved.list", "nothing"), ("view.transparencyGrid", "session"), ("view.snapToGlyph.options", "preferences"), + ("view.snapToPixel.options", "preferences"), ]; for (id, writes) in expected { let got = listed.iter().find(|(c, _)| *c == id).map(|(_, w)| w.clone()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2352776651..6c231dc7e5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4033,6 +4033,38 @@ fn snap_to_pixel_rounds_drawing_and_moves() { assert_eq!((b.x0, b.y0), (17.0, 16.0)); } +/// Pixel Snapping Options (`view.snapToPixel.options`): with While Drawing off a rectangle drawn +/// with Snap to Pixel on keeps its fractional corners while a move still lands on whole pixels, and +/// with While Moving off a move keeps its fractional offset while drawing snaps again. +#[test] +fn pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds() { + let mut s = session(); + let v = ViewInfo { snap_to_pixel: true, smart_guides: false, snap_to_point: false, ..Default::default() }; + let drag = |s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)| { + s.select_tool(tool, v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, from.0, from.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to.0, to.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to.0, to.1), v).unwrap(); + }; + let bounds = |s: &Session, id| { + let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0, b.x1, b.y1) + }; + s.execute("view.snapToPixel.options", &json!({"drawing": false})).unwrap(); + drag(&mut s, "rectangle", (10.25, 10.5), (60.5, 40.25)); + let id = s.doc().unwrap().selection.objects[0]; + assert_eq!(bounds(&s, id), (10.25, 10.5, 60.5, 40.25), "drawing does not snap"); + drag(&mut s, "selection", (30.0, 30.0), (37.5, 34.75)); + assert_eq!(bounds(&s, id).0, 18.0, "moving still snaps the left edge"); + assert_eq!(bounds(&s, id).1, 15.0, "moving still snaps the top edge"); + s.execute("view.snapToPixel.options", &json!({"drawing": true, "moving": false})).unwrap(); + drag(&mut s, "selection", (40.0, 30.0), (45.25, 33.5)); + assert_eq!((bounds(&s, id).0, bounds(&s, id).1), (23.25, 18.5), "moving does not snap"); + drag(&mut s, "rectangle", (100.25, 100.5), (140.5, 130.75)); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_eq!(bounds(&s, drawn), (100.0, 101.0, 141.0, 131.0), "drawing snaps again"); +} + #[test] fn shaper_turns_rough_strokes_into_live_shapes_and_scribbles_punch_fills() { let mut s = session(); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 14669fd357..1a08737424 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -2736,3 +2736,33 @@ fn snap_to_glyph_options_read_set_and_reset() { s.execute("prefs.reset", &json!({})).unwrap(); assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all); } + +/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving +/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and +/// values change nothing, preferences saved without the group read it as all on, and resetting the +/// preferences turns them all back on. +#[test] +fn pixel_snapping_options_read_set_and_reset() { + let mut s = Session::new(); + let all = json!({"drawing": true, "moving": true, "scaling": true}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all); + let set = json!({"drawing": true, "moving": false, "scaling": true}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({"moving": false})).unwrap(), set); + assert_eq!(s.execute("prefs.get", &json!({"key": "pixelSnap"})).unwrap(), set); + assert!(!s.prefs.pixel_snap.moving && s.prefs.pixel_snap.drawing && s.prefs.pixel_snap.scaling); + for bad in [json!({"moving": 1}), json!({"rotating": false})] { + assert!(s.execute("view.snapToPixel.options", &bad).is_err(), "{bad}"); + assert!(s.execute("prefs.set", &json!({"key": "pixelSnap", "value": bad})).is_err(), "{bad}"); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), set, "{bad}"); + } + s.execute("prefs.set", &json!({"key": "pixelSnap", "value": {"scaling": false}})).unwrap(); + let both = json!({"drawing": true, "moving": false, "scaling": false}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), both); + // Preferences written before the group existed, and a group that names only some options. + let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap(); + assert_eq!(older.pixel_snap, vectorcraft_tools::PixelSnap::default()); + let partial: Prefs = serde_json::from_value(json!({"pixelSnap": {"drawing": false}})).unwrap(); + assert_eq!(partial.pixel_snap, vectorcraft_tools::PixelSnap { drawing: false, moving: true, scaling: true }); + s.execute("prefs.reset", &json!({})).unwrap(); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index ad1549140f..0f4fb4ad2b 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -25,7 +25,8 @@ pub struct ViewInfo { /// View → Pixel Preview: while it is on, the tools use no Smart Guides. pub pixel_preview: bool, pub show_bbox: bool, - /// View → Snap to Pixel: drawing and moving land on whole pixels (points at 72 ppi). + /// View → Snap to Pixel: drawing, moving and scaling land on whole pixels (points at 72 ppi), + /// each while its Pixel Snapping option (`view.snapToPixel.options`) is on. pub snap_to_pixel: bool, /// View → Snap to Point: picked points (a transform's reference point) land on anchors. pub snap_to_point: bool, @@ -355,6 +356,7 @@ impl Session { // Snap to Grid and Snap to Pixel are exclusive, as in Illustrator; left both on, the grid // wins instead of pixels quietly rounding every drag to whole points (#1816). snap_to_pixel: view.snap_to_pixel && !view.snap_to_grid, + pixel_snap: self.prefs.pixel_snap, snap_to_point: view.snap_to_point, snap_tangent: self.prefs.snap_tangent, snap_perpendicular: self.prefs.snap_perpendicular, diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 342feb568c..26df6b78aa 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -195,7 +195,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), ("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"), ("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"), - ("view.snapToPixel", "Snap to Pixel", "", "{} toggle: drawing and moving land on whole pixels"), + ( + "view.snapToPixel", + "Snap to Pixel", + "", + "{} toggle: drawing, moving and scaling land on whole pixels, each while its option in view.snapToPixel.options is on", + ), ( "view.snapToGlyph", "Snap to Glyph", diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 741e962290..e6db6069c7 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -117,6 +117,53 @@ impl GlyphSnap { } } +/// The Pixel Snapping Options (`view.snapToPixel.options`): which edits View › Snap to Pixel lands +/// on whole pixels. All on by default. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct PixelSnap { + /// While Drawing: points placed by the drawing tools, ruler origins and measurements. + pub drawing: bool, + /// While Moving: the selection, its anchors and segments, artboards and ruler guides moved. + pub moving: bool, + /// While Scaling: the edges a bounding-box, Free Transform, Scale tool, artboard or slice + /// handle drags. + pub scaling: bool, +} + +impl Default for PixelSnap { + fn default() -> Self { + Self { drawing: true, moving: true, scaling: true } + } +} + +impl PixelSnap { + /// These options with the ones `p` names (booleans), or why `p` can't set them. + pub fn merged(self, p: &serde_json::Value) -> Result { + let mut o = serde_json::to_value(self).map_err(|e| e.to_string())?; + match (p, o.as_object_mut()) { + (serde_json::Value::Null, _) => {} + (serde_json::Value::Object(given), Some(cur)) => { + for (k, v) in given { + let slot = cur.get_mut(k).ok_or_else(|| format!("unknown Pixel Snapping option `{k}`"))?; + *slot = serde_json::Value::Bool(v.as_bool().ok_or_else(|| format!("`{k}` must be true or false"))?); + } + } + _ => return Err("the Pixel Snapping options must be an object".into()), + } + serde_json::from_value(o).map_err(|e| e.to_string()) + } +} + +/// The kind of edit a snap serves, which picks the Pixel Snapping option that applies to it +/// ([`ToolContext::snaps_to_pixel`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PixelOp { + Drawing, + Moving, + Scaling, +} + /// Read-only context a tool sees. pub struct ToolContext<'a> { pub doc: &'a Document, @@ -141,8 +188,11 @@ pub struct ToolContext<'a> { pub snap_to_grid: bool, /// Bounding box shown (View → Show/Hide Bounding Box). pub show_bbox: bool, - /// View → Snap to Pixel. + /// View → Snap to Pixel. Which edits it snaps is [`Self::pixel_snap`]'s choice + /// ([`Self::snaps_to_pixel`]). pub snap_to_pixel: bool, + /// The Pixel Snapping Options: whether Snap to Pixel snaps drawing, moving and scaling. + pub pixel_snap: PixelSnap, /// View → Snap to Point: with Smart Guides off, dragged selections, drawn points and picked /// points (a transform's reference point) land on anchors and ruler guides within /// [`Self::snap_tolerance`]. @@ -342,6 +392,16 @@ impl ToolContext<'_> { let (dist, ang, dx, dy) = xform::measure(a, b); format!("D: {}\nAngle: {ang:.1}°\n{}", self.len(dist), self.offset_label(dx, dy)) } + /// Does View › Snap to Pixel land an edit of kind `op` on whole pixels: is it on, with the + /// Pixel Snapping option for `op` on too? + pub fn snaps_to_pixel(&self, op: PixelOp) -> bool { + self.snap_to_pixel + && match op { + PixelOp::Drawing => self.pixel_snap.drawing, + PixelOp::Moving => self.pixel_snap.moving, + PixelOp::Scaling => self.pixel_snap.scaling, + } + } /// What Snap to Grid snaps to: the grid's subdivisions (or its lines without any). pub fn grid_step(&self) -> f64 { self.doc.grid.spacing / self.doc.grid.subdivisions.max(1) as f64 diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 3addd48785..3030414b38 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -66,7 +66,7 @@ use crate::meshedit::{MeshEdit, grid_of}; use crate::pathtype::{self, BracketDrag, near_bracket}; use crate::rulerguide::GuideEdit; use crate::select::{MoveSnap, hit_center, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at, selection_bounds}; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Clone, Debug)] enum State { @@ -1465,11 +1465,11 @@ impl DirectSelectionTool { } out.push(Action::Begin("Move".into())); self.state = State::MoveAnchors { start, grab, began: true, segment }; - self.anchor_snap = Some(PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); + self.anchor_snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); self.line_end = line_end_leave(cx, grab); // A segment held by a point along it lands its anchors on the grid (the box round // them, an edge on a gridline on each axis), not that point (#3835). - let grid = segment && (cx.snap_to_grid || cx.snap_to_pixel); + let grid = segment && (cx.snap_to_grid || cx.snaps_to_pixel(PixelOp::Moving)); self.partial_grid = grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()))); } @@ -1505,8 +1505,8 @@ impl DirectSelectionTool { // them and the objects selected whole (`path.moveAnchors`), as an anchor drag // does, while Alt is up; the other anchors of a partly selected path stay in // place. The history names the move or the copy at the end. - self.partial_snap = (!cx.selection.anchors.is_empty()).then(|| PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); - let grid = self.partial_snap.is_some() && grab.is_none() && (cx.snap_to_grid || cx.snap_to_pixel); + self.partial_snap = (!cx.selection.anchors.is_empty()).then(|| PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); + let grid = self.partial_snap.is_some() && grab.is_none() && (cx.snap_to_grid || cx.snaps_to_pixel(PixelOp::Moving)); self.partial_grid = grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()))); let copy = ev.mods.alt && self.partial_snap.is_none(); @@ -1514,8 +1514,8 @@ impl DirectSelectionTool { self.state = State::MoveObject { start, grab, hold, began: true, deselect: None }; if grab.is_some() { // Alt can go down or up at any time: gather both while nothing has moved. - self.anchor_snap = Some(PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); - self.copy_snap = Some(PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, &Selection::default()))); + self.anchor_snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); + self.copy_snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, &Selection::default()))); // As a move with the Selection tool does ([`MoveSnap::new`]). let back = cx.smart_guides && !cx.snap_to_grid && cx.snap_to_last_location; self.last_location = back.then(|| (Targets::last_location(cx), selection_bounds(cx))); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 0ac443c731..7ce48bdc1e 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -634,6 +634,33 @@ fn snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor( assert!(labels.is_empty(), "{labels:?}"); } +/// Pixel Snapping Options › While Moving off: a direct-selected anchor dragged with Snap to Pixel +/// on keeps its fractional offset; with the option on it lands on whole pixels. +#[test] +fn an_anchor_drag_follows_the_while_moving_option() { + use crate::PixelSnap; + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(100.3, 100.4, 200.3, 200.4)); + d.insert(Some(l), 0, vectorcraft_doc::Node::path(id, square, vectorcraft_doc::Appearance::default_art())).unwrap(); + let s = anchors_of(id, &[(0, 0)]); + let p = paint(); + let moved = |pixel_snap: PixelSnap| { + let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.3, 100.4)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 106.3, 105.4)); + let Some(Action::Preview(command, v)) = a.last() else { panic!("{a:?}") }; + assert_eq!(command, "path.moveAnchors"); + Vec2::new(v["dx"].as_f64().unwrap_or(f64::NAN), v["dy"].as_f64().unwrap_or(f64::NAN)) + }; + let m = moved(PixelSnap { moving: false, ..PixelSnap::default() }); + assert!((m - Vec2::new(6.0, 5.0)).hypot() < 1e-9, "{m:?}"); + let m = moved(PixelSnap { drawing: false, scaling: false, moving: true }); + assert!((m - Vec2::new(5.7, 4.6)).hypot() < 1e-9, "{m:?}"); +} + /// A click (no drag) on an anchor that is selected with others, whether the whole path is or /// some of its anchors, selects that anchor alone, as in Illustrator: a press keeps the /// selection so a drag moves it all, the release without a drag narrows it. Shift still diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index e4811418c7..beb0346b90 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -216,10 +216,10 @@ impl GestureTool { } /// Does a straight Knife cut snap to anchors and paths? Only with Smart Guides on, which Snap to - /// Pixel and Snap to Grid turn off (`PointSnap::new`). Its ends snap as the Pencil's straight - /// line's do: the press, and the release unless Shift keeps it on a 45° step. + /// Pixel (for drawing) and Snap to Grid turn off (`PointSnap::new`). Its ends snap as the + /// Pencil's straight line's do: the press, and the release unless Shift keeps it on a 45° step. fn knife_snaps(&self, cx: &ToolContext) -> bool { - self.id == "knife" && self.straight && cx.smart_guides && !cx.snap_to_pixel && !cx.snap_to_grid + self.id == "knife" && self.straight && cx.smart_guides && !cx.snaps_to_pixel(crate::PixelOp::Drawing) && !cx.snap_to_grid } /// Does the end of a straight line snap: the Pencil's Alt line's, or a straight Knife cut's diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 6f0b50d4b5..006f498b6e 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -3,6 +3,7 @@ use super::{ Affine, GlyphSnap, GuideStyle, Handle, HitOptions, Line, NodeId, OrientedBox, Overlay, ParamCurve, ParamCurveDeriv, ParamCurveNearest, PathSeg, Point, Rect, ScreenFrame, ToolContext, Vec2, constrain_angle_from, hit_test, }; +use crate::PixelOp; /// Where curves `a` and `b` cross near `p`: a point projected from one onto the other and back /// settles where they meet (none when they don't nearby). @@ -100,11 +101,29 @@ pub struct PointSnap { /// The smart guide targets, or with Smart Guides off those of Snap to Point, and how near (in /// screen pixels) they pull; none with pixels or the grid snapping instead, or nothing on. targets: Option<(Targets, f64)>, + /// The kind of edit the point serves: whether Snap to Pixel rounds it + /// ([`ToolContext::snaps_to_pixel`]). + op: PixelOp, } impl PointSnap { + /// Snapping for a drawn point. pub fn new(cx: &ToolContext, targets: impl FnOnce() -> Targets) -> Self { - let targets = if cx.snap_to_pixel || cx.snap_to_grid { + Self::for_op(cx, PixelOp::Drawing, targets) + } + + /// Snapping for a moved point (an anchor, or the selection held by one). + pub fn moving(cx: &ToolContext, targets: impl FnOnce() -> Targets) -> Self { + Self::for_op(cx, PixelOp::Moving, targets) + } + + /// Snapping for a dragged handle that scales ([`Self::snap_scale`]). + pub fn scaling(cx: &ToolContext, targets: impl FnOnce() -> Targets) -> Self { + Self::for_op(cx, PixelOp::Scaling, targets) + } + + fn for_op(cx: &ToolContext, op: PixelOp, targets: impl FnOnce() -> Targets) -> Self { + let targets = if cx.snaps_to_pixel(op) || cx.snap_to_grid { None } else if cx.smart_guides { // Snap to Point keeps pulling points onto the ruler guides with Smart Guides on (#812). @@ -116,7 +135,7 @@ impl PointSnap { } else { None }; - Self { targets } + Self { targets, op } } /// Snapping for a point placed anywhere, as a drawing tool's ([`DrawSnap`]) is: the art in the @@ -135,7 +154,7 @@ impl PointSnap { /// showing why. Pixels and the grid round it before Shift turns it onto its angle. pub fn snap_from(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> (Point, Vec) { let keep = |q: Point| from.and_then(|f| f.constrained(q)).unwrap_or(q); - if cx.snap_to_pixel { + if cx.snaps_to_pixel(self.op) { return (keep(Point::new(p.x.round(), p.y.round())), vec![]); } if cx.snap_to_grid { @@ -148,9 +167,10 @@ impl PointSnap { } /// Snap a bounding-box resize ([`Targets::snap_scale`]) as [`Self::snap`] snaps a point. With - /// Snap to Pixel on, the corner or side the handle moves lines up with whole pixels, and with - /// Snap to Grid on it lines up with the nearest gridline, however far that is; neither shows - /// guides. Otherwise the handle snaps to the targets [`Self::new`] gathered. + /// Snap to Pixel on for scaling, the corner or side the handle moves lines up with whole + /// pixels, and with Snap to Grid on it lines up with the nearest gridline, however far that + /// is; neither shows guides. Otherwise the handle snaps to the targets [`Self::scaling`] + /// gathered. pub fn snap_scale( &self, cx: &ToolContext, @@ -160,7 +180,7 @@ impl PointSnap { proportional: bool, from_center: bool, ) -> (Affine, Vec) { - let step = if cx.snap_to_pixel { + let step = if cx.snaps_to_pixel(PixelOp::Scaling) { Some(1.0) } else if cx.snap_to_grid { Some(cx.grid_step()).filter(|s| s.is_finite() && *s > 0.0) @@ -327,7 +347,15 @@ impl SnapKey { revision: cx.revision, exclude: exclude.to_vec(), screen: cx.screen, - view: [cx.smart_guides, cx.snap_to_point, cx.snap_to_pixel, cx.snap_to_grid, cx.guides, cx.snap_tangent, cx.snap_perpendicular], + view: [ + cx.smart_guides, + cx.snap_to_point, + cx.snaps_to_pixel(PixelOp::Drawing), + cx.snap_to_grid, + cx.guides, + cx.snap_tangent, + cx.snap_perpendicular, + ], snap_to_glyph: (cx.snap_to_glyph && cx.smart_guides && cx.alignment_guides).then_some(cx.glyph_snap), style: GuideStyle::of(cx), tolerances: [cx.snapping_tolerance, cx.snap_tolerance], @@ -381,7 +409,7 @@ impl DrawSnap { /// Guides snapping tolerance (the Knife's straight cut). The targets serve this press only. pub fn press_on_paths(&mut self, cx: &ToolContext, p: Point) -> Point { let targets = Targets::for_drawing(cx.doc, &[], visible(cx), None).styled(cx).anchors_and_paths(); - self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)) })); + self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing })); self.snap(cx, p, None) } diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 41b9f517ee..cb0fdfc1dc 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -168,13 +168,13 @@ impl Targets { /// or nothing for a copy, which leaves it behind), styled as `cx` asks, and with Smart Guides › /// Spacing Guides the objects it spaces itself evenly with ([`Self::snap_rect`]). With Smart /// Guides › Snap to Last Location, a move (not a copy, which has nothing in `exclude`) goes back - /// to where it began when it comes near ([`Self::snap_back`]), unless Snap to Pixel is on. + /// to where it began when it comes near ([`Self::snap_back`]), unless Snap to Pixel snaps moves. pub fn for_move(cx: &ToolContext, exclude: &[NodeId]) -> Self { let mut t = Self::collect(cx.doc, exclude, None).styled(cx); if cx.spacing_guides { t.boxes = object_boxes(cx.doc, &cx.selection.objects); } - t.last_location = cx.snap_to_last_location && !cx.snap_to_pixel && !exclude.is_empty(); + t.last_location = cx.snap_to_last_location && !cx.snaps_to_pixel(crate::PixelOp::Moving) && !exclude.is_empty(); t } @@ -189,9 +189,9 @@ impl Targets { /// Targets that hold nothing but Smart Guides › Snap to Last Location ([`Self::snap_back`]), /// styled as `cx` asks: for a move of the selection whose other snaps come from other targets, /// such as paths selected whole that Direct Selection moves held by an anchor. Snap to Pixel - /// turns it off, as it does every Smart Guides snap. + /// snapping moves turns it off, as it does every Smart Guides snap. pub fn last_location(cx: &ToolContext) -> Self { - Self { last_location: cx.snap_to_last_location && !cx.snap_to_pixel, ..Self::default() }.styled(cx) + Self { last_location: cx.snap_to_last_location && !cx.snaps_to_pixel(crate::PixelOp::Moving), ..Self::default() }.styled(cx) } /// Targets for scaling the selection: the other art, styled as `cx` asks, and with Smart Guides › diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index d73cd2297f..e64bf5bcc6 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -58,7 +58,7 @@ mod context; mod cursor; mod input; -pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, ScreenFrame, ToolContext}; +pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext}; pub use cursor::Cursor; pub use input::{Action, Mods, PenPose, PointerEvent, PointerKind, ToolKey}; @@ -542,6 +542,7 @@ pub(crate) mod testutil { snap_to_grid: false, show_bbox: true, snap_to_pixel: false, + pixel_snap: crate::PixelSnap::default(), snap_to_point: true, snap_tangent: true, snap_perpendicular: true, diff --git a/crates/tools/src/rulerguide.rs b/crates/tools/src/rulerguide.rs index a90770d3fb..8e037443cb 100644 --- a/crates/tools/src/rulerguide.rs +++ b/crates/tools/src/rulerguide.rs @@ -17,7 +17,7 @@ use vectorcraft_doc::{Guide, NodeId}; use vectorcraft_geom::{Point, Rect}; use crate::guides::{PointSnap, Targets}; -use crate::{Action, Cursor, Overlay, PointerEvent, PointerKind, ToolContext}; +use crate::{Action, Cursor, Overlay, PixelOp, PointerEvent, PointerKind, ToolContext}; /// The ruler guide under `p`, by its index in `guide.list`: the nearest within the selection /// tolerance (the newest of equals). @@ -123,7 +123,7 @@ struct GuideSnap { impl GuideSnap { fn new(cx: &ToolContext) -> Self { let targets = || Targets::collect(cx.doc, &[], None); - let targets = if cx.snap_to_pixel || cx.snap_to_grid { + let targets = if cx.snaps_to_pixel(PixelOp::Moving) || cx.snap_to_grid { None } else if cx.smart_guides { Some((targets().styled(cx), cx.snapping_tolerance)) @@ -136,7 +136,8 @@ impl GuideSnap { } /// Where a guide dragged to `v` (the x of a vertical one, the y of a horizontal one) goes: - /// with Shift on the nearest ruler tick, else on whole pixels, the grid or a target. + /// with Shift on the nearest ruler tick, else on whole pixels (Snap to Pixel's While Moving + /// option), the grid or a target. fn snap(&mut self, cx: &ToolContext, vertical: bool, v: f64, shift: bool) -> f64 { self.snapped.clear(); if shift { @@ -144,7 +145,7 @@ impl GuideSnap { let origin = if vertical { origin.x } else { origin.y }; return origin + cx.unit.snap_to_ruler_tick(v - origin, cx.zoom); } - if cx.snap_to_pixel { + if cx.snaps_to_pixel(PixelOp::Moving) { return v.round(); } if cx.snap_to_grid { diff --git a/crates/tools/src/rulerguide/tests.rs b/crates/tools/src/rulerguide/tests.rs index f80f31c776..b4b7c256d3 100644 --- a/crates/tools/src/rulerguide/tests.rs +++ b/crates/tools/src/rulerguide/tests.rs @@ -253,6 +253,24 @@ fn new_ruler_guide_alt_snaps_on_the_effective_axis() { } } +/// A guide dragged out of a ruler snaps to whole pixels with Snap to Pixel only while the Pixel +/// Snapping Options' While Moving is on; While Drawing and While Scaling do not change it. +#[test] +fn new_ruler_guide_follows_the_while_moving_option() { + use crate::PixelSnap; + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let off = ToolContext { smart_guides: false, snap_to_point: false, snap_to_pixel: true, ..cx(&d, &s, &p) }; + for (pixel_snap, expected) in + [(PixelSnap { moving: false, ..PixelSnap::default() }, 226.4), (PixelSnap { drawing: false, scaling: false, moving: true }, 226.0)] + { + let c = ToolContext { pixel_snap, ..off }; + let mut g = NewGuide::new(&c, true, None); + let actions = g.pointer(&c, &ev(PointerKind::Drag, 226.4, 237.6, Mods::default()), true); + assert_eq!(actions.last(), Some(&Action::Preview("guide.add".into(), json!({"vertical": true, "pos": expected}))), "{pixel_snap:?}"); + } +} + /// With Smart Guides off, Snap to Point pulls a dragged guide onto the anchors (within its /// distance), not the edges' midpoints. #[test] diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 05b81ae049..70060ebc2b 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -56,7 +56,7 @@ use crate::pie::{self, PieDrag}; use crate::rulerguide::GuideEdit; use crate::shaperwidget; use crate::typewidget; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids}; +use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids}; /// Direction is read on screen, even in a turned view. Within three pixels of the press's /// horizontal position, retain the previous rule so hand jitter does not flip it. @@ -228,8 +228,9 @@ fn distance_overlays(cx: &ToolContext, to: DistanceTo) -> Vec { /// Snap to Grid lands its edges on the grid (#740), taking over from the rest; otherwise Smart /// Guides line its bounds up with the other art, and with them off, View → Snap to Point lands the /// point it was grabbed by (an anchor pressed near, else the pressed point) on an anchor or a ruler -/// guide. Snap to Pixel puts its top-left on whole pixels. A copy (Alt, which can go down or up at -/// any time during the drag) leaves the original behind, so it snaps to the original too. +/// guide. Snap to Pixel puts its top-left on whole pixels while its While Moving option is on. A +/// copy (Alt, which can go down or up at any time during the drag) leaves the original behind, so +/// it snaps to the original too. pub(crate) struct MoveSnap { bounds: Option, targets: Option, @@ -314,7 +315,7 @@ impl MoveSnap { } } } - if cx.snap_to_pixel + if cx.snaps_to_pixel(PixelOp::Moving) && let Some(b) = self.bounds { d = Vec2::new((b.x0 + d.x).round() - b.x0, (b.y0 + d.y).round() - b.y0); @@ -388,7 +389,7 @@ impl MoveSnap { guides = ov; } } - if cx.snap_to_pixel + if cx.snaps_to_pixel(PixelOp::Moving) && let Some(b) = self.bounds { let at = Point::new(b.x0, b.y0) + d; @@ -1655,7 +1656,7 @@ impl SelectionTool { // What the handle moves snaps as a dragged point does: to pixels or the // grid, else with Smart Guides to the other objects, else with Snap to // Point to their anchors; the ruler guides with Snap to Point. - self.targets = Some(PointSnap::new(cx, || Targets::for_scale(cx))); + self.targets = Some(PointSnap::scaling(cx, || Targets::for_scale(cx))); self.last_backquote = false; self.last_box_pos = None; self.state = State::Scaling { handle, bx, areas }; diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index c41056b7aa..63ca697c7d 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1794,6 +1794,51 @@ fn handle_drag_lands_what_it_moves_on_whole_pixels() { assert!(near(r, Rect::new(100.0, 100.0, 212.0, 231.0)), "{r:?}"); } +/// Pixel Snapping Options › While Scaling off: a handle drag keeps the fractional size it is +/// dragged to with Snap to Pixel on, and turned back on, the drag lands on whole pixels again; While +/// Drawing and While Moving do not change it. +#[test] +fn handle_drag_follows_the_while_scaling_option() { + use crate::PixelSnap; + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let drag = |pixel_snap: PixelSnap| { + let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)); + scaled(&t.pointer(&c, &ev(PointerKind::Drag, 212.4, 230.7))) + }; + let r = drag(PixelSnap { scaling: false, ..PixelSnap::default() }); + assert!(near(r, Rect::new(100.0, 100.0, 212.4, 230.7)), "{r:?}"); + let r = drag(PixelSnap { drawing: false, moving: false, scaling: true }); + assert!(near(r, Rect::new(100.0, 100.0, 212.0, 231.0)), "{r:?}"); +} + +/// Pixel Snapping Options › While Moving off: a move keeps its fractional offset with Snap to +/// Pixel on, and Smart Guides › Snap to Last Location works again for it. +#[test] +fn move_follows_the_while_moving_option() { + use crate::PixelSnap; + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let pixel_snap = PixelSnap { moving: false, ..PixelSnap::default() }; + let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let snap = MoveSnap::new(&c); + let (dv, _) = snap.snap(&c, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false); + assert!((dv - Vec2::new(3.3, 4.6)).hypot() < 1e-9, "{dv:?}"); + let on = ToolContext { pixel_snap: PixelSnap::default(), ..c }; + let (dv, _) = MoveSnap::new(&on).snap(&on, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false); + assert!((dv - Vec2::new(3.0, 5.0)).hypot() < 1e-9, "{dv:?}"); + let back = ToolContext { smart_guides: true, snap_to_last_location: true, snapping_tolerance: 10.0, ..c }; + assert!(Targets::for_move(&back, &back.selection.objects).snap_back(None, Vec2::new(1.0, 1.0), back.snap_tol()).is_some()); + let pixels = ToolContext { pixel_snap: PixelSnap::default(), ..back }; + assert!(Targets::for_move(&pixels, &pixels.selection.objects).snap_back(None, Vec2::new(1.0, 1.0), pixels.snap_tol()).is_none()); +} + /// #2054: with Smart Guides off, View › Snap to Point lands a dragged handle on another /// object's anchor or a ruler guide within its distance (2 px); with Smart Guides on, the /// ruler guides still pull it within the Snapping Tolerance (4 px), as a move does (#1534). diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index fb291796f7..66728b4826 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -236,7 +236,7 @@ impl ShapeTool { self.selection = if let Some((handle, bx)) = self.over_handle(cx, ev.pos) { let is_area = |id: &vectorcraft_doc::NodeId| cx.doc.node(*id).is_some_and(is_area_type); let areas = cx.selection.objects.iter().any(is_area); - Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::new(cx, || Targets::for_scale(cx))), last: None }) + Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling(cx, || Targets::for_scale(cx))), last: None }) } else { match hit_center(cx, ev.pos, cx.point_tol()) { Some((_, hold)) => Some(SelectionDrag::Move { start: ev.pos, hold, began: false, snap: Box::new(MoveSnap::new(cx)) }), diff --git a/crates/tools/src/slice.rs b/crates/tools/src/slice.rs index 69bbf9051f..0f804a8ef6 100644 --- a/crates/tools/src/slice.rs +++ b/crates/tools/src/slice.rs @@ -161,7 +161,7 @@ struct ResizeSnap { impl ResizeSnap { fn new(cx: &ToolContext) -> Self { - Self { art: PointSnap::new(cx, || Targets::collect(cx.doc, &[], None)), rulers: Targets::rulers(cx) } + Self { art: PointSnap::scaling(cx, || Targets::collect(cx.doc, &[], None)), rulers: Targets::rulers(cx) } } /// Snap the resize `a` ([`scale_for_drag`]) of the slice `rect` by `handle` as [`snap`] snaps diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index 4ffd435af6..5af642c44b 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -37,7 +37,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::{BLUE, polygon, rect_corners}; use crate::bbox::{Handle, hit_handle, scale_for_drag}; use crate::guides::{DrawSnap, Leave, Targets}; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Clone, Copy, Debug)] enum Drag { @@ -205,11 +205,12 @@ impl ArtboardTool { self.copy_targets = cx.smart_guides.then(|| Targets::for_artboard(cx.doc, usize::MAX, &[]).styled(cx)); } - /// Snap a dragged handle: to whole pixels, the grid, or Smart Guides (in that order, as when - /// drawing). With Smart Guides the bleed edge `bleed` beyond the handle may snap instead. + /// Snap a dragged handle: to whole pixels (Snap to Pixel's While Scaling option), the grid, or + /// Smart Guides (in that order, as when drawing). With Smart Guides the bleed edge `bleed` + /// beyond the handle may snap instead. fn snap_handle(&mut self, cx: &ToolContext, p: Point, bleed: Vec2) -> Point { self.guides.clear(); - if cx.snap_to_pixel { + if cx.snaps_to_pixel(PixelOp::Scaling) { return Point::new(p.x.round(), p.y.round()); } if cx.snap_to_grid { @@ -222,12 +223,13 @@ impl ArtboardTool { q } - /// Snap a move (or an Alt-drag `copy`) of `rect` by `d`: its top-left to whole pixels or the - /// grid, or any of its edges and centre to Smart Guides. Returns the snapped delta. + /// Snap a move (or an Alt-drag `copy`) of `rect` by `d`: its top-left to whole pixels (Snap to + /// Pixel's While Moving option) or the grid, or any of its edges and centre to Smart Guides. + /// Returns the snapped delta. fn snap_move(&mut self, cx: &ToolContext, rect: Rect, d: Vec2, copy: bool) -> Vec2 { self.guides.clear(); let tl = Point::new(rect.x0, rect.y0); - if cx.snap_to_pixel { + if cx.snaps_to_pixel(PixelOp::Moving) { return Vec2::new((tl.x + d.x).round() - tl.x, (tl.y + d.y).round() - tl.y); } if cx.snap_to_grid { diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index bd7c0c0ecd..2d137153fc 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -248,7 +248,7 @@ impl Tool for FreeTransformTool { self.drag = None; let Some(bx) = selection_box(cx) else { return vec![] }; if let Some(op) = self.classify(cx, &bx, p, ev.mods) { - self.targets = op.handle().is_some().then(|| PointSnap::new(cx, || Targets::for_scale(cx))); + self.targets = op.handle().is_some().then(|| PointSnap::scaling(cx, || Targets::for_scale(cx))); self.drag = Some(Drag { op, bx, start: p, began: false }); } vec![] diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index cccb1ebcae..0b575c503c 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -43,7 +43,7 @@ pub(crate) fn end_point(cx: &ToolContext, snap: &mut DrawSnap, a: Point, p: Poin return a; } let u = d / len; - let to_point = cx.snap_to_point && !(cx.smart_guides || cx.snap_to_grid || cx.snap_to_pixel); + let to_point = cx.snap_to_point && !(cx.smart_guides || cx.snap_to_grid || cx.snaps_to_pixel(crate::PixelOp::Drawing)); let s = if to_point { snap.measure(cx, p, None) } else { p }; let q = a + u * (s - a).dot(u); let leave = crate::guides::Leave::segment(cx, a, true); diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 5cabbed6b8..263c0ea5e4 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -238,8 +238,11 @@ impl Tool for TransformTool { return out; } d.began = true; - // The selection moves, so only the other objects are targets. - self.snap = Some(PointSnap::new(cx, || Targets::collect(cx.doc, &cx.selection.objects, None))); + // The selection moves, so only the other objects are targets. The Scale tool's + // drag scales; the others move the art about the reference point. + let targets = || Targets::collect(cx.doc, &cx.selection.objects, None); + self.snap = + Some(if self.kind == TransformKind::Scale { PointSnap::scaling(cx, targets) } else { PointSnap::moving(cx, targets) }); out.push(Action::Begin(self.kind.label().into())); } let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p)); diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 9b862cf636..f5c4c727dd 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -78,7 +78,8 @@ pub(super) const ISOLATION_BUTTON: &str = "cb-isolation"; /// less, the menu is left out so those controls still fit the narrowest window. const ARTBOARD_SNAPPING_WIDTH: f32 = 900.0; -/// The Control bar's snapping quick access; every change uses its existing command. +/// The Control bar's snapping quick access; every change uses its existing command, and Pixel +/// Snapping Options… opens the dialog of `view.snapToPixel.options`. fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.menu_button(tl!("Snapping"), |ui| { for (label, cmd, on) in [ @@ -92,6 +93,10 @@ fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, cmd, json!({})); } } + if ui.button(tl!("Pixel Snapping Options…")).clicked() { + ui.close(); + crate::menus::invoke(app, "view.snapToPixel.options", json!({})); + } ui.separator(); for (key, label, on) in [ ("alignmentGuides", tl!("Alignment Guides"), app.session.prefs.alignment_guides), diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 626ff8c66e..3db9e3e45d 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2247,6 +2247,82 @@ fn the_control_bar_snapping_menu_shares_glyph_and_alignment_settings() { check(&nodes, "Alignment Guides", true); } +/// The Control bar's Snapping menu opens Pixel Snapping Options with the current options; OK sets +/// the three choices the dialog shows, and a dialog closed without OK changes nothing. +#[test] +fn the_control_bar_snapping_menu_opens_pixel_snapping_options() { + struct RestoreLanguage(crate::i18n::Lang); + impl Drop for RestoreLanguage { + fn drop(&mut self) { + crate::i18n::set_current(self.0); + } + } + let _language = RestoreLanguage(crate::i18n::current()); + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("view.snapToPixel.options", json!({"moving": false})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 400.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let center = |nodes: &[(egui::accesskit::NodeId, egui::accesskit::Node)], name: &str| { + let n = nodes.iter().find(|(_, n)| n.label() == Some(name)).map(|(_, n)| n.clone()).unwrap_or_else(|| panic!("missing {name}")); + let b = n.bounds().expect("a visible menu control"); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + let click = |app: &mut crate::VectorcraftApp, at: egui::Pos2| { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(app, vec![press(false)]); + frame(app, vec![]); + frame(app, vec![]) + }; + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + let menu = center(&nodes, "Snapping"); + let nodes = click(&mut app, menu); + let entry = center(&nodes, "Pixel Snapping Options…"); + click(&mut app, entry); + let d = app.ui.dialog.as_ref().expect("Pixel Snapping Options"); + assert_eq!(d.kind, crate::dialogs::pixel_snap_options::KIND); + assert_eq!(serde_json::Value::Object(d.fields.clone()), json!({"drawing": true, "moving": false, "scaling": true})); + // While View › Snap to Pixel is off, the dialog says the options wait for it. + // A new window is laid out unseen in its first frame, so the second frame is read. + let note = |app: &mut crate::VectorcraftApp| { + let mut nodes = vec![]; + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + let shown = |text: &str| nodes.iter().any(|(_, n)| n.label().or(n.value()).is_some_and(|l| l.contains(text))); + (shown("Snap to Pixel While Drawing"), shown("take effect when View › Snap to Pixel is on")) + }; + assert!(!app.ui.view.snap_to_pixel); + assert_eq!(note(&mut app), (true, true), "the note shows with Snap to Pixel off"); + app.ui.view.snap_to_pixel = true; + assert_eq!(note(&mut app), (true, false), "the note is hidden with Snap to Pixel on"); + let before = app.session.prefs.pixel_snap; + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("drawing".into(), json!(false)); + app.ui.dialog = None; + assert_eq!(app.session.prefs.pixel_snap, before, "a dialog closed without OK changes nothing"); + crate::menus::invoke(&mut app, "view.snapToPixel.options", json!({})); + let d = app.ui.dialog.as_mut().expect("Pixel Snapping Options"); + d.fields.insert("drawing".into(), json!(false)); + d.fields.insert("moving".into(), json!(true)); + d.fields.insert("scaling".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.prefs.pixel_snap, vectorcraft_tools::PixelSnap { drawing: false, moving: true, scaling: false }); +} + /// The window the Control bar docking tests draw the bar in. const DOCK_SCREEN: egui::Rect = egui::Rect { min: egui::Pos2::ZERO, max: egui::pos2(1200.0, 300.0) }; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 197f8faaaa..6040ac8fb4 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -88,6 +88,7 @@ pub mod perspective_grid; pub mod perspective_options; pub mod perspective_plane; pub mod perspective_presets; +pub mod pixel_snap_options; pub mod place; pub mod placement_options; pub mod plugin; @@ -452,6 +453,7 @@ registry! { LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, NavigatorPanelOptions: [navigator_panel_options::KIND] => navigator_panel_options::SPEC, PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, + PixelSnapOptions: [pixel_snap_options::KIND] => pixel_snap_options::SPEC, RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, diff --git a/crates/ui-egui/src/dialogs/pixel_snap_options.rs b/crates/ui-egui/src/dialogs/pixel_snap_options.rs new file mode 100644 index 0000000000..43b369e105 --- /dev/null +++ b/crates/ui-egui/src/dialogs/pixel_snap_options.rs @@ -0,0 +1,46 @@ +//! Pixel Snapping Options (the Control bar's Snapping menu): whether View › Snap to Pixel lands +//! drawing, moving and scaling on whole pixels. OK runs `view.snapToPixel.options` (the options live +//! in the preferences); Cancel leaves them as they were. +//! +//! Fields: `drawing`, `moving` and `scaling` (bool). While Snap to Pixel is off, the options stay +//! editable and a note says they take effect once it is on. + +use serde_json::{Value, json}; + +use super::DialogSpec; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Pixel Snapping Options. +pub const KIND: &str = "pixelSnapOptions"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Pixel Snapping Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + +/// Open the dialog with the current options. +pub fn open(app: &mut VectorcraftApp) { + app.ui.dialog = Some(Dialog::new(KIND, json!(app.session.prefs.pixel_snap))); +} + +fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str) { + let v = d.bool(key); + if widgets::check(ui, text, v, true) { + d.fields.insert(key.into(), json!(!v)); + } +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + check(ui, d, "drawing", tl!("Snap to Pixel While Drawing")); + check(ui, d, "moving", tl!("Snap to Pixel While Moving")); + check(ui, d, "scaling", tl!("Snap to Pixel While Scaling")); + if !app.ui.view.snap_to_pixel { + let dim = Tokens::get(ui.ctx()).text_dim; + ui.label(egui::RichText::new(tl!("These options take effect when View › Snap to Pixel is on.")).color(dim)); + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + super::run_and_close(app, "view.snapToPixel.options", Value::Object(d.fields.clone())) +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..f911da3d24 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6159,6 +6159,13 @@ axis Y Axis Y ос Area Text Текст в зона # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Измерване на текста по границите на глифа +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Опции за прилепване към пиксел + Pixel Snapping Options… Опции за прилепване към пиксел… + Snap to Pixel While Drawing Прилепване към пиксел при рисуване + Snap to Pixel While Moving Прилепване към пиксел при преместване + Snap to Pixel While Scaling Прилепване към пиксел при мащабиране + These options take effect when View › Snap to Pixel is on. Тези опции действат, когато Изглед › Прилепване към пиксел е включено. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Показване на опциите за прилепване към глиф Hide Snap to Glyph Options Скриване на опциите за прилепване към глиф diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..6e80a4e798 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6218,6 +6218,12 @@ axis Y Axis Y osa Area Text Tekst u oblasti # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Mjeri tekst po granicama glifa + Pixel Snapping Options Opcije prianjanja uz piksel + Pixel Snapping Options… Opcije prianjanja uz piksel… + Snap to Pixel While Drawing Prilijepi uz piksel pri crtanju + Snap to Pixel While Moving Prilijepi uz piksel pri pomjeranju + Snap to Pixel While Scaling Prilijepi uz piksel pri skaliranju + These options take effect when View › Snap to Pixel is on. Ove opcije djeluju kada je uključeno Prikaz › Prilijepi uz piksel. Show Snap to Glyph Options Prikaži opcije prianjanja uz glif Hide Snap to Glyph Options Sakrij opcije prianjanja uz glif Snap to Glyph Options Opcije prianjanja uz glif diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..1d76aec580 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6676,6 +6676,13 @@ theme Appearance Aparença Area Text Text d’àrea # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Mesura el text pels límits del glif +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Opcions d’ajust al píxel + Pixel Snapping Options… Opcions d’ajust al píxel… + Snap to Pixel While Drawing Ajusta al píxel en dibuixar + Snap to Pixel While Moving Ajusta al píxel en moure + Snap to Pixel While Scaling Ajusta al píxel en escalar + These options take effect when View › Snap to Pixel is on. Aquestes opcions tenen efecte quan Visualitza › Ajusta al píxel està activat. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Mostra les opcions d’ajust al glif Hide Snap to Glyph Options Amaga les opcions d’ajust al glif diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..ce3e45bf6a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6713,6 +6713,13 @@ axis Y Axis osa Y Area Text Text v oblasti # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Měřit text podle hranic glyfů +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Možnosti přichytávání k obrazovým bodům + Pixel Snapping Options… Možnosti přichytávání k obrazovým bodům… + Snap to Pixel While Drawing Přichytávat k obrazovým bodům při kreslení + Snap to Pixel While Moving Přichytávat k obrazovým bodům při přesouvání + Snap to Pixel While Scaling Přichytávat k obrazovým bodům při změně velikosti + These options take effect when View › Snap to Pixel is on. Tyto volby se uplatní, když je zapnuto Zobrazení › Přichytávat k obrazovým bodům. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Zobrazit možnosti přichytávání ke glyfům Hide Snap to Glyph Options Skrýt možnosti přichytávání ke glyfům diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..5072f73bfb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6176,6 +6176,13 @@ axis Y Axis Y-akse Area Text Områdetekst # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Mål tekst efter glyfafgrænsning +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Indstillinger for fastgørelse til pixel + Pixel Snapping Options… Indstillinger for fastgørelse til pixel… + Snap to Pixel While Drawing Fastgør til pixel ved tegning + Snap to Pixel While Moving Fastgør til pixel ved flytning + Snap to Pixel While Scaling Fastgør til pixel ved skalering + These options take effect when View › Snap to Pixel is on. Disse indstillinger virker, når Vis › Fastgør til pixel er slået til. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Vis indstillinger for fastgørelse til tegn Hide Snap to Glyph Options Skjul indstillinger for fastgørelse til tegn diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..40a6b3121d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6304,6 +6304,13 @@ axis Y Axis Y-Achse Area Text Flächentext # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Text an Glyphenbegrenzung messen +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Optionen für „An Pixel ausrichten“ + Pixel Snapping Options… Optionen für „An Pixel ausrichten“… + Snap to Pixel While Drawing Beim Zeichnen an Pixel ausrichten + Snap to Pixel While Moving Beim Verschieben an Pixel ausrichten + Snap to Pixel While Scaling Beim Skalieren an Pixel ausrichten + These options take effect when View › Snap to Pixel is on. Diese Optionen wirken, wenn Ansicht › An Pixel ausrichten aktiviert ist. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Optionen für „An Glyphe ausrichten“ einblenden Hide Snap to Glyph Options Optionen für „An Glyphe ausrichten“ ausblenden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..89aa77d3d3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6664,6 +6664,13 @@ axis Y Axis Άξονας Y Area Text Κείμενο περιοχής # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Μέτρηση κειμένου με βάση τα όρια γλυφής +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Επιλογές προσκόλλησης σε εικονοστοιχείο + Pixel Snapping Options… Επιλογές προσκόλλησης σε εικονοστοιχείο… + Snap to Pixel While Drawing Προσκόλληση σε εικονοστοιχείο κατά τη σχεδίαση + Snap to Pixel While Moving Προσκόλληση σε εικονοστοιχείο κατά τη μετακίνηση + Snap to Pixel While Scaling Προσκόλληση σε εικονοστοιχείο κατά την αλλαγή κλίμακας + These options take effect when View › Snap to Pixel is on. Αυτές οι επιλογές ισχύουν όταν είναι ενεργή η επιλογή Προβολή › Προσκόλληση σε εικονοστοιχείο. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Εμφάνιση επιλογών προσκόλλησης σε γλυφή Hide Snap to Glyph Options Απόκρυψη επιλογών προσκόλλησης σε γλυφή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..1755a07ec5 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6655,6 +6655,13 @@ axis Y Axis Eje Y Area Text Texto de área # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Medir el texto por los límites del glifo +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Opciones de ajuste a píxel + Pixel Snapping Options… Opciones de ajuste a píxel… + Snap to Pixel While Drawing Ajustar a píxel al dibujar + Snap to Pixel While Moving Ajustar a píxel al mover + Snap to Pixel While Scaling Ajustar a píxel al escalar + These options take effect when View › Snap to Pixel is on. Estas opciones se aplican cuando Ver › Ajustar a píxel está activado. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Mostrar opciones de ajuste a glifo Hide Snap to Glyph Options Ocultar opciones de ajuste a glifo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..c7e4c338d7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6743,6 +6743,13 @@ axis Y Axis Y-akseli Area Text Alueteksti # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Mittaa teksti merkin rajoista +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Pikseliin kohdistuksen asetukset + Pixel Snapping Options… Pikseliin kohdistuksen asetukset… + Snap to Pixel While Drawing Kohdista pikseliin piirrettäessä + Snap to Pixel While Moving Kohdista pikseliin siirrettäessä + Snap to Pixel While Scaling Kohdista pikseliin skaalattaessa + These options take effect when View › Snap to Pixel is on. Nämä asetukset ovat voimassa, kun Näytä › Kohdista pikseliin on käytössä. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Näytä merkkiin kohdistuksen asetukset Hide Snap to Glyph Options Piilota merkkiin kohdistuksen asetukset diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..144f8a6d7e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6708,6 +6708,13 @@ axis Y Axis Axe Y Area Text Texte captif # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Mesurer le texte d’après les limites du glyphe +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Options de magnétisme du pixel + Pixel Snapping Options… Options de magnétisme du pixel… + Snap to Pixel While Drawing Magnétisme du pixel lors du dessin + Snap to Pixel While Moving Magnétisme du pixel lors du déplacement + Snap to Pixel While Scaling Magnétisme du pixel lors de la mise à l’échelle + These options take effect when View › Snap to Pixel is on. Ces options s’appliquent lorsque Affichage › Magnétisme du pixel est activé. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Afficher les options de magnétisme du glyphe Hide Snap to Glyph Options Masquer les options de magnétisme du glyphe diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..1553546852 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4556,6 +4556,12 @@ antiAlias Sharp शार्प Show Slice Numbers स्लाइस नंबर दिखाएँ Show Slices स्लाइस दिखाएँ Show smooth color wheel चिकनी रंग पहिया दिखाएँ + Pixel Snapping Options पिक्सेल पर स्नैप ऑप्शन्स + Pixel Snapping Options… पिक्सेल पर स्नैप ऑप्शन्स… + Snap to Pixel While Drawing ड्रॉ करते समय पिक्सेल के लिए स्नैप + Snap to Pixel While Moving मूव करते समय पिक्सेल के लिए स्नैप + Snap to Pixel While Scaling स्केल करते समय पिक्सेल के लिए स्नैप + These options take effect when View › Snap to Pixel is on. ये ऑप्शन्स तब लागू होते हैं जब व्यू › पिक्सेल के लिए स्नैप चालू हो। Show Snap to Glyph Options ग्लिफ़ पर स्नैप ऑप्शन्स दिखाएँ Show Swatch Bounds स्वॉच की सीमाएँ दिखाएँ Show Swatch Kinds स्वॉच प्रकार दिखाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..62f8ea56c1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6696,6 +6696,13 @@ axis Y Axis Y tengely Area Text Területszöveg # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Szöveg mérése a glifahatárok szerint +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Pixelhez illesztés beállításai + Pixel Snapping Options… Pixelhez illesztés beállításai… + Snap to Pixel While Drawing Illesztés pixelhez rajzoláskor + Snap to Pixel While Moving Illesztés pixelhez mozgatáskor + Snap to Pixel While Scaling Illesztés pixelhez méretezéskor + These options take effect when View › Snap to Pixel is on. Ezek a beállítások akkor érvényesek, ha a Nézet › Illesztés pixelhez be van kapcsolva. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Glifához illesztés beállításainak megjelenítése Hide Snap to Glyph Options Glifához illesztés beállításainak elrejtése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..bbd52236e8 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6176,6 +6176,13 @@ axis Y Axis Sumbu Y Area Text Teks area # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Ukur teks menurut batas glif +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Opsi snap ke piksel + Pixel Snapping Options… Opsi snap ke piksel… + Snap to Pixel While Drawing Snap ke piksel saat menggambar + Snap to Pixel While Moving Snap ke piksel saat memindahkan + Snap to Pixel While Scaling Snap ke piksel saat menskalakan + These options take effect when View › Snap to Pixel is on. Opsi ini berlaku saat Tampilan › Snap ke piksel aktif. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Tampilkan opsi snap ke glif Hide Snap to Glyph Options Sembunyikan opsi snap ke glif diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..9d3e6cccb5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6338,6 +6338,13 @@ axis Y Axis Asse Y Area Text Testo in area # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Misura il testo in base ai limiti del glifo +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Opzioni di aggancio ai pixel + Pixel Snapping Options… Opzioni di aggancio ai pixel… + Snap to Pixel While Drawing Aggancia ai pixel durante il disegno + Snap to Pixel While Moving Aggancia ai pixel durante lo spostamento + Snap to Pixel While Scaling Aggancia ai pixel durante il ridimensionamento + These options take effect when View › Snap to Pixel is on. Queste opzioni hanno effetto quando Visualizza › Aggancia ai pixel è attivo. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Mostra opzioni di aggancio a glifo Hide Snap to Glyph Options Nascondi opzioni di aggancio a glifo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..338f34b85a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6403,6 +6403,13 @@ axis Y Axis Y 軸 Area Text エリア内文字 # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds 文字を字形の境界で測定 +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options ピクセルにスナップのオプション + Pixel Snapping Options… ピクセルにスナップのオプション… + Snap to Pixel While Drawing 描画時にピクセルにスナップ + Snap to Pixel While Moving 移動時にピクセルにスナップ + Snap to Pixel While Scaling 拡大・縮小時にピクセルにスナップ + These options take effect when View › Snap to Pixel is on. これらのオプションは、表示 › ピクセルにスナップがオンのときに有効になります。 # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options グリフにスナップのオプションを表示 Hide Snap to Glyph Options グリフにスナップのオプションを隠す diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..8e30337139 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6737,6 +6737,13 @@ swatch Bright Violet კაშკაშა იისფერი Area Text არის ტექსტი # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds ტექსტის გაზომვა გლიფის საზღვრებით +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options პიქსელზე მიბმის პარამეტრები + Pixel Snapping Options… პიქსელზე მიბმის პარამეტრები… + Snap to Pixel While Drawing პიქსელზე მიბმა ხატვისას + Snap to Pixel While Moving პიქსელზე მიბმა გადაადგილებისას + Snap to Pixel While Scaling პიქსელზე მიბმა მასშტაბირებისას + These options take effect when View › Snap to Pixel is on. ეს პარამეტრები მოქმედებს, როცა ხედი › პიქსელზე მიბმა ჩართულია. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options გლიფზე მიბმის პარამეტრების ჩვენება Hide Snap to Glyph Options გლიფზე მიბმის პარამეტრების დამალვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..6ccb3ea254 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6299,6 +6299,13 @@ axis Y Axis Y축 Area Text 영역 문자 # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds 글리프 경계로 문자 측정 +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options 픽셀에 스냅 옵션 + Pixel Snapping Options… 픽셀에 스냅 옵션… + Snap to Pixel While Drawing 그리는 동안 픽셀에 스냅 + Snap to Pixel While Moving 이동하는 동안 픽셀에 스냅 + Snap to Pixel While Scaling 크기를 조절하는 동안 픽셀에 스냅 + These options take effect when View › Snap to Pixel is on. 이 옵션은 보기 › 픽셀에 스냅이 켜져 있을 때 적용됩니다. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options 글리프에 스냅 옵션 표시 Hide Snap to Glyph Options 글리프에 스냅 옵션 숨기기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..3ab41bc575 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6227,6 +6227,13 @@ axis Y Axis Y-as Area Text Vlaktekst # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Tekst meten op glyphbegrenzing +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Opties voor uitlijnen op pixel + Pixel Snapping Options… Opties voor uitlijnen op pixel… + Snap to Pixel While Drawing Uitlijnen op pixel bij tekenen + Snap to Pixel While Moving Uitlijnen op pixel bij verplaatsen + Snap to Pixel While Scaling Uitlijnen op pixel bij schalen + These options take effect when View › Snap to Pixel is on. Deze opties werken wanneer Beeld › Uitlijnen op pixel is ingeschakeld. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Opties voor uitlijnen op glyph tonen Hide Snap to Glyph Options Opties voor uitlijnen op glyph verbergen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..ccc06104f9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6567,6 +6567,13 @@ axis Y Axis Oś Y Area Text Tekst akapitowy # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Mierz tekst według granic glifów +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Opcje przyciągania do pikseli + Pixel Snapping Options… Opcje przyciągania do pikseli… + Snap to Pixel While Drawing Przyciągaj do pikseli podczas rysowania + Snap to Pixel While Moving Przyciągaj do pikseli podczas przesuwania + Snap to Pixel While Scaling Przyciągaj do pikseli podczas skalowania + These options take effect when View › Snap to Pixel is on. Te opcje działają, gdy włączona jest opcja Widok › Przyciągaj do pikseli. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Pokaż opcje przyciągania do glifów Hide Snap to Glyph Options Ukryj opcje przyciągania do glifów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..3dd3c2cb48 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6628,6 +6628,13 @@ axis Y Axis Eixo Y Area Text Texto de Área # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Medir Texto pelos Limites do Glifo +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Opções de Ajuste ao Pixel + Pixel Snapping Options… Opções de Ajuste ao Pixel… + Snap to Pixel While Drawing Ajustar ao Pixel ao Desenhar + Snap to Pixel While Moving Ajustar ao Pixel ao Mover + Snap to Pixel While Scaling Ajustar ao Pixel ao Dimensionar + These options take effect when View › Snap to Pixel is on. Essas opções têm efeito quando Exibir › Ajustar ao Pixel está ativado. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Mostrar Opções de Ajuste ao Glifo Hide Snap to Glyph Options Ocultar Opções de Ajuste ao Glifo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..6e937fe89b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6690,6 +6690,13 @@ theme Appearance Оформление Area Text Текст в области # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Измерять текст по границам глифа +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Параметры привязки к пикселю + Pixel Snapping Options… Параметры привязки к пикселю… + Snap to Pixel While Drawing Привязать к пикселю при рисовании + Snap to Pixel While Moving Привязать к пикселю при перемещении + Snap to Pixel While Scaling Привязать к пикселю при масштабировании + These options take effect when View › Snap to Pixel is on. Эти параметры действуют, когда включено Просмотр › Привязать к пикселю. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Показать параметры привязки к глифу Hide Snap to Glyph Options Скрыть параметры привязки к глифу diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..09381d2014 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6694,6 +6694,13 @@ axis Y Axis Y-axel Area Text Områdestext # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Mät text efter glyfgränser +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Alternativ för fäst mot pixel + Pixel Snapping Options… Alternativ för fäst mot pixel… + Snap to Pixel While Drawing Fäst mot pixel vid ritning + Snap to Pixel While Moving Fäst mot pixel vid flyttning + Snap to Pixel While Scaling Fäst mot pixel vid skalning + These options take effect when View › Snap to Pixel is on. De här alternativen gäller när Visa › Fäst mot pixel är på. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Visa alternativ för fäst mot glyf Hide Snap to Glyph Options Dölj alternativ för fäst mot glyf diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..873702c4d1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6669,6 +6669,13 @@ axis Y Axis Y ekseni Area Text Alan Metni # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Yazıyı Glif Sınırlarına Göre Ölç +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Piksel'e Yapışma Seçenekleri + Pixel Snapping Options… Piksel'e Yapışma Seçenekleri… + Snap to Pixel While Drawing Çizerken Piksel'e Yapış + Snap to Pixel While Moving Taşırken Piksel'e Yapış + Snap to Pixel While Scaling Ölçeklerken Piksel'e Yapış + These options take effect when View › Snap to Pixel is on. Bu seçenekler Görünüm › Piksel'e Yapış açıkken etkili olur. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Glif'e Yapışma Seçeneklerini Göster Hide Snap to Glyph Options Glif'e Yapışma Seçeneklerini Gizle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..7e9262e286 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6318,6 +6318,13 @@ axis Y Axis Вісь Y Area Text Текст в області # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Вимірювати текст за межами гліфа +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Параметри прив’язки до пікселя + Pixel Snapping Options… Параметри прив’язки до пікселя… + Snap to Pixel While Drawing Прив’язати до пікселя під час малювання + Snap to Pixel While Moving Прив’язати до пікселя під час переміщення + Snap to Pixel While Scaling Прив’язати до пікселя під час масштабування + These options take effect when View › Snap to Pixel is on. Ці параметри діють, коли ввімкнено Перегляд › Прив’язати до пікселя. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Показати параметри прив’язки до гліфа Hide Snap to Glyph Options Приховати параметри прив’язки до гліфа diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..37eb6eed8c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6319,6 +6319,13 @@ axis Y Axis Trục Y Area Text Chữ vùng # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds Đo chữ theo giới hạn glyph +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options Tùy chọn hút vào pixel + Pixel Snapping Options… Tùy chọn hút vào pixel… + Snap to Pixel While Drawing Hút vào pixel khi vẽ + Snap to Pixel While Moving Hút vào pixel khi di chuyển + Snap to Pixel While Scaling Hút vào pixel khi thay đổi tỉ lệ + These options take effect when View › Snap to Pixel is on. Các tùy chọn này có hiệu lực khi Hiển thị › Hút vào pixel đang bật. # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options Hiện tùy chọn hút vào glyph Hide Snap to Glyph Options Ẩn tùy chọn hút vào glyph diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..40da21d992 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6551,6 +6551,13 @@ axis Y Axis Y 轴 Area Text 区域文字 # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds 按字形边界度量文字 +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options 对齐像素选项 + Pixel Snapping Options… 对齐像素选项… + Snap to Pixel While Drawing 绘制时对齐像素 + Snap to Pixel While Moving 移动时对齐像素 + Snap to Pixel While Scaling 缩放时对齐像素 + These options take effect when View › Snap to Pixel is on. 这些选项在“视图 › 对齐像素”打开时生效。 # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options 显示靠齐字符选项 Hide Snap to Glyph Options 隐藏靠齐字符选项 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..8f5cbf3f7d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6356,6 +6356,13 @@ axis Y Axis Y 軸 Area Text 區域文字 # Transform panel menu › Measure Type by Glyph Bounds. Measure Type by Glyph Bounds 依字符邊界測量文字 +# Control bar › Snapping › Pixel Snapping Options… (view.snapToPixel.options). + Pixel Snapping Options 靠齊像素選項 + Pixel Snapping Options… 靠齊像素選項… + Snap to Pixel While Drawing 繪製時靠齊像素 + Snap to Pixel While Moving 移動時靠齊像素 + Snap to Pixel While Scaling 縮放時靠齊像素 + These options take effect when View › Snap to Pixel is on. 這些選項會在「檢視 › 靠齊像素」開啟時生效。 # Character panel menu › Show Snap to Glyph Options (#4232). Show Snap to Glyph Options 顯示靠齊字符選項 Hide Snap to Glyph Options 隱藏靠齊字符選項 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 9d30b2a5b6..447f468867 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -206,7 +206,7 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { } } -/// The dialogs the Envelope, Variables, Pathfinder, Repeat, type, graph and View commands open when called without +/// The dialogs the Envelope, Variables, Pathfinder, Pixel Snapping, Repeat, type, graph and View commands open when called without /// params; whether `id` was one of them. fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { // Envelope Distort: Warp Options, Envelope Mesh and Envelope Options, from the selection. @@ -226,6 +226,11 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { crate::dialogs::pathfinder_options::open(app); return true; } + // Pixel Snapping Options: a dialog with the current options. + if id == "view.snapToPixel.options" && p.as_object().is_none_or(|o| o.is_empty()) { + crate::dialogs::pixel_snap_options::open(app); + return true; + } // Repeat Options: a dialog with the selected repeat's current values. if id == "object.repeat.options" && p.as_object().is_none_or(|o| o.is_empty()) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 20a2c58314..ed23382cef 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -196,7 +196,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), ("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"), ("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"), - ("view.snapToPixel", "Snap to Pixel", "", "{} toggle: drawing and moving land on whole pixels"), + ( + "view.snapToPixel", + "Snap to Pixel", + "", + "{} toggle: drawing, moving and scaling land on whole pixels, each while its option in view.snapToPixel.options is on", + ), ( "view.snapToGlyph", "Snap to Glyph", diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..9ea6823bfc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1777,7 +1777,7 @@ vectorcraft-cli run --cmd file.new --params '{"width":600,"height":200}' --cmd ### Parameter schemas Some commands have a machine-readable parameter schema: at present a small set including `view.capsLock`, `view.saved.new`, -`view.saved.edit`, `view.saved.list`, `view.transparencyGrid`, `view.snapToGlyph.options` and `engine.apiReference` +`view.saved.edit`, `view.saved.list`, `view.transparencyGrid`, `view.snapToGlyph.options`, `view.snapToPixel.options` and `engine.apiReference` (most of the catalogue still documents params in prose only; schemas grow command by command). The engine's `engine.commands` list gives such a command a `schema` field: an object schema in the shape of JSON Schema 2020-12 (https://json-schema.org/draft/2020-12). Its root has `$schema` (the 2020-12 dialect), `description` when the @@ -1830,9 +1830,10 @@ as the English gives them. An omitted value with a `default` takes it (`rotation` 0 in `view.saved.new`); the journal keeps the params as they were given. Saved steps played from a journal or an action keep a key the schema does not name, unless its value nests -more than 16 levels deep, and the values of the parameters it names are checked as in a new call. The schemas of built-in commands belong to API level 3 +more than 16 levels deep, and the values of the parameters it names are checked as in a new call. The schemas of built-in commands belong to API level 4 (`vectorcraft_engine::schemas::API_VERSION`); a change to any of them raises the level. Level 2 added -`engine.apiReference`; level 3 says that `rotation` in `view.saved.new` and `view.saved.list` turns clockwise. Commands that plug-ins add have no schema here. +`engine.apiReference`; level 3 says that `rotation` in `view.saved.new` and `view.saved.list` turns clockwise; level 4 +adds `view.snapToPixel.options`. Commands that plug-ins add have no schema here. `engine.apiReference {}` → `{markdown}` returns the command API reference, written from these schemas each time it runs; no file of it is kept. It needs no open document and changes nothing. The reference has a `##` section for each @@ -5636,6 +5637,23 @@ know or a value that isn't a boolean is refused and changes nothing. {"name":"run_command","arguments":{"command":"view.snapToGlyph.options","params":{"angular":false,"anchors":false}}} ``` +The Pixel Snapping Options (the desktop app's Control bar › Snapping menu › Pixel Snapping Options…, described on the +help page, +): +`view.snapToPixel.options {drawing?, moving?, +scaling?}` (or `prefs.get`/`prefs.set` with key `pixelSnap`, a partial object) reads and sets which edits View › Snap to +Pixel lands on whole pixels. All three are on by default, which is VectorCraft's own default. `drawing` covers the +points the drawing tools place, the rulers' origin and measured points; `moving` covers the selection, its anchors and +segments, artboards and ruler guides moved by dragging, and the Rotate, Reflect and Shear tools' drags; `scaling` +covers the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag. An edit +whose option is off snaps as it does with Snap to Pixel off. With Snap to Pixel off, the options do nothing. `{}` reads +them; a key it doesn't know or a value that isn't a boolean is refused and changes nothing. Align New Objects to Pixel +Grid and the objects' pixel-aligned property (see Align to Pixel Grid) do not depend on these options. + +```json +{"name":"run_command","arguments":{"command":"view.snapToPixel.options","params":{"scaling":false}}} +``` + With Smart Guides on, a bounding-box handle dragged with the Selection or Free Transform tool (`mods.shift` proportional, `mods.alt` from the centre) lands on another object's anchor or centre (labelled "anchor" or "center"), else its corners and side line up with the edges and centres of the other objects and the artboards (a @@ -5863,8 +5881,8 @@ Preferences. `prefs.reset` resets the preferences at once, without the question. `prefs.export {path?}` writes the preferences as a JSON file, `{"format": "vectorcraft-preferences", "version": 1, "prefs": {…}}`, and replies `{path, count}`; without `path` it replies `{data, count}` with the file's text. The file -holds every preference `prefs.list` lists and the `eyedropper`, `perspectiveWidget`, `pathfinder` and `glyphSnap` -groups. It leaves out the folder preferences (`fontsFolder`, `pluginsFolder`, `recoveryFolder`, `templatesFolder`) and +holds every preference `prefs.list` lists and the `eyedropper`, `perspectiveWidget`, `pathfinder`, `glyphSnap` and +`pixelSnap` groups. It leaves out the folder preferences (`fontsFolder`, `pluginsFolder`, `recoveryFolder`, `templatesFolder`) and saved presets. An export over 1 MB, the most `prefs.import` reads, is an error and writes nothing. `prefs.import {path | data}` applies such a file and replies `{imported}`, the number of preferences it set. It checks every value first, as `prefs.set` does: a file over 1 MB, malformed JSON, another `format`, a newer diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 086d4cfc0d..5bb79dbe9e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -900,6 +900,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close). - Four brightness themes, persistent preferences. - **Snapping quick access (#6164):** Control bar › Snapping includes Snap to Glyph (`view.snapToGlyph`) and Alignment Guides (`prefs.set`, `alignmentGuides`). The headless pointer/accessibility test `the_control_bar_snapping_menu_shares_glyph_and_alignment_settings` covers both commands, independent state, checked states after reopening, and all eight menu rows within a 1200 × 400-point window. Floating-panel parity remains unverified; scores and estimates unchanged. + - **Pixel Snapping Options:** Control bar › Snapping › Pixel Snapping Options… sets whether View › Snap to Pixel snaps drawing, moving and scaling, each on by default (`view.snapToPixel.options`, the `pixelSnap` preference group; [the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/draw-pixel-perfect-art.html)). Tests: `pixel_snapping_options_read_set_and_reset`, `pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds`, `handle_drag_follows_the_while_scaling_option`, `move_follows_the_while_moving_option`, `an_anchor_drag_follows_the_while_moving_option`, `new_ruler_guide_follows_the_while_moving_option` and `the_control_bar_snapping_menu_opens_pixel_snapping_options`. Scores and estimates unchanged. - **Measure tools and Snap to Glyph:** with Snap to Glyph, Smart Guides and Alignment Guides on, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag land within the snapping tolerance on the guides of live type that the Character panel's options allow, except Anchor Point, and a Shift-drag's end slides along its 45° step to them. The guide shows during the drag. This is VectorCraft's own rule (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`); scores and estimates unchanged. - **Drawing readout without the rubber band:** with Enable Rubber Band for the Pen or Curvature tool off and Measurement Labels on, the Pen, the Smart Pen and the Curvature tool hide the preview segment but still show the D / Angle / dX / dY readout at the snapped pointer before the next click, and the Curvature tool also shows it when going on from the current end of a selected path. Measurement Labels show distance and placement while drawing ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)), and the rubber band preference turns off the path preview ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html)). Showing the readout with the rubber band off is VectorCraft's own rule (`pen::tests::measurement_label_shows_with_the_rubber_band_off`, and `the_measurement_label_shows_with_the_rubber_band_off` in `draw2::curvature::tests` and `addons::smart_pen::tests`); scores and estimates unchanged. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default: on, pink behind OpenType substitutions on screen — ligatures, contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set`, #394). About 14 stored options still do nothing yet (the rest of #394: Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation language, scratch disks, the legacy clipboard, Touch Workspace). From dc7b0d0c903556508582dc64b21e1b819154f4be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 02:31:55 -0800 Subject: [PATCH 11/28] Layers: layer and object rows held near the list's top or bottom edge scroll a long list While layer or object rows are dragged in the Layers panel, holding the pointer within 28 points of the list's top or bottom edge scrolls the list that way, faster nearer the edge, and it keeps scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt). The Libraries panel's edge-scroll helper moves to panels.rs and both panels use it. Scrolling stops on release, when the pointer leaves the list's width, and for other drags such as the eye or lock column. --- crates/ui-egui/src/panels.rs | 20 +++ crates/ui-egui/src/panels/layers.rs | 10 +- crates/ui-egui/src/panels/layers/tests.rs | 150 ++++++++++++++++++++++ crates/ui-egui/src/panels/libraries.rs | 20 +-- docs/target-app-parity.md | 3 +- 5 files changed, 182 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index cbad3dd34f..340e355f3a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -521,6 +521,26 @@ pub(crate) fn rows_take_delete(ctx: &egui::Context) -> bool { has_row_keys(ctx, layers::ROW_KEYS) || has_row_keys(ctx, appearance::ROW_KEYS) } +/// How near a scrolled list's top or bottom edge a drag scrolls it ([`scroll_at_edges`]). +const DRAG_SCROLL_EDGE: f32 = 28.0; + +/// While something is dragged near the top or bottom edge of a scrolled list (`ui`: its contents), +/// scroll that way, faster nearer the edge, and draw the next frame so a pointer held still keeps +/// it scrolling. The pointer must be over the list's width. +pub(crate) fn scroll_at_edges(ui: &mut Ui) { + let Some(pos) = ui.ctx().pointer_hover_pos() else { return }; + let view = ui.clip_rect(); + if !view.x_range().contains(pos.x) { + return; + } + let speed = |depth: f32| if (0.0..DRAG_SCROLL_EDGE).contains(&depth) { 2.0 + 10.0 * (1.0 - depth / DRAG_SCROLL_EDGE) } else { 0.0 }; + let delta = speed(pos.y - view.top()) - speed(view.bottom() - pos.y); + if delta != 0.0 { + ui.scroll_with_delta(vec2(0.0, delta)); + ui.ctx().request_repaint(); + } +} + /// [`crate::i18n::label_or_name`] in the UI language. pub(crate) fn label_or_name(s: &str, built_in: bool) -> &str { crate::i18n::label_or_name(crate::i18n::current(), s, built_in) diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 0ac14d243d..73d6171701 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -19,7 +19,8 @@ //! to Outline and the row's layer to Preview (`layer.outlineOthers`), or switches every layer to //! Preview when the others are in Outline (`layer.previewAll`). //! - Dragging rows moves them above, below or into a layer or group (`layer.move`, a drop line or -//! a box shows where); Alt copies them. A dimmed copy of the row follows the pointer. Layers +//! a box shows where); Alt copies them. A dimmed copy of the row follows the pointer, and rows +//! held near the top or bottom edge of the list scroll it, faster nearer the edge. Layers //! dropped in the empty space under the last row go below the bottom layer. Dropped on the trash //! they are deleted, on New Layer duplicated. //! - Deleting rows from the panel (the trash, rows dropped on it, Delete Selection, Delete and @@ -304,6 +305,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for r in list.get(range).unwrap_or_default() { row(ui, &view, r, &mut out); } + // Rows held near the list's top or bottom edge scroll it, so a row out of view can + // take the drop. + if egui::DragAndDrop::payload::(ui.ctx()).is_some_and(|d| matches!(*d, LayersDrag::Rows(_))) + && ui.input(|i| i.pointer.primary_down()) + { + super::scroll_at_edges(ui); + } }, ) }); diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2143bd1ee3..90091dceeb 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1232,6 +1232,156 @@ fn dragging_rows_moves_them_into_other_layers_and_alt_copies() { let _ = (layer, c); } +/// One headless frame of the panel on a short screen (300 × 260) with `events` (Alt held when +/// `alt`): for every row name painted inside the list's view, its center, and the view. +fn short_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, alt: bool) -> (HashMap, egui::Rect) { + let mut events = events; + events.insert(0, egui::Event::ModifiersChanged(egui::Modifiers { alt, ..Default::default() })); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 260.0)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + // The rows' eye column dividers are drawn clipped to the list's view. + let border = Tokens::get(ctx).input_border; + let view = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::LineSegment { stroke, .. } if stroke.color == border && c.clip_rect.height() < screen.height() => Some(c.clip_rect), + _ => None, + }) + .unwrap_or(egui::Rect::NOTHING); + let mut names = HashMap::new(); + for c in &out.shapes { + if let egui::Shape::Text(t) = &c.shape + && t.galley.text().starts_with("Layer ") + && view.contains_rect(c.clip_rect) + { + let center = t.pos + t.galley.size() / 2.0; + if c.clip_rect.contains(center) { + names.insert(t.galley.text().to_string(), center); + } + } + } + (names, view) +} + +/// A document of 30 empty layers named `Layer 1` (the bottom one) to `Layer 30` (the top one): +/// more rows than [`short_frame`]'s list shows. +fn thirty_layers() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + for i in 2..=30 { + app.session.execute("layer.new", &json!({"top": true, "name": format!("Layer {i}")})).unwrap(); + } + app +} + +/// The layers' names, bottom first. +fn layer_names(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +/// Hold the button still at `at` (a row is held) until `name`'s row is fully in view; → its center. +fn hold_until(app: &mut VectorcraftApp, ctx: &egui::Context, at: egui::Pos2, name: &str, alt: bool) -> Option { + short_frame(app, ctx, vec![egui::Event::PointerMoved(at)], alt); + for _ in 0..500 { + let (names, view) = short_frame(app, ctx, vec![], alt); + if let Some(&c) = names.get(name) + && c.y - ROW_MEDIUM / 2.0 >= view.top() + && c.y + ROW_MEDIUM / 2.0 <= view.bottom() + { + return Some(c); + } + } + None +} + +#[test] +fn rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view() { + let mut app = thirty_layers(); + let ctx = egui::Context::default(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let (names, view) = short_frame(&mut app, &ctx, vec![], false); + assert!(names.contains_key("Layer 30") && !names.contains_key("Layer 1"), "the list overflows: {names:?}"); + let before = (undo(&app), layer_names(&app)); + // Layer 30 held still just above the list's bottom edge: the list scrolls down to Layer 1. + let grab = names["Layer 30"]; + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)], false); + short_frame(&mut app, &ctx, vec![button(grab, true)], false); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab + vec2(0.0, 6.0))], false); + let edge = egui::pos2(grab.x, view.bottom() - 3.0); + let target = hold_until(&mut app, &ctx, edge, "Layer 1", false).expect("Layer 1 scrolled into view while the row was held"); + assert_eq!((undo(&app), layer_names(&app)), before, "scrolling alone changes nothing"); + // Dropped on the upper edge of Layer 1's row: above it. + let drop = target - vec2(0.0, ROW_MEDIUM * 0.4); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)], false); + short_frame(&mut app, &ctx, vec![button(drop, false)], false); + let names = layer_names(&app); + assert_eq!(&names[..2], ["Layer 1", "Layer 30"], "{names:?}"); + assert_eq!(undo(&app), before.0 + 1); + // Released, the list stays where it is with the pointer in the top band. + let (rows, _) = short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(egui::pos2(drop.x, view.top() + 3.0))], false); + for _ in 0..10 { + assert_eq!(short_frame(&mut app, &ctx, vec![], false).0, rows, "no scrolling after the release"); + } + // Layer 2, Alt-dragged to the top edge: the list scrolls back up, and dropped on the lower edge + // of Layer 29's row a copy goes below it. + let grab = rows["Layer 2"]; + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)], true); + short_frame(&mut app, &ctx, vec![button(grab, true)], true); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab - vec2(0.0, 6.0))], true); + let (_, view) = short_frame(&mut app, &ctx, vec![], true); + let target = hold_until(&mut app, &ctx, egui::pos2(grab.x, view.top() + 3.0), "Layer 29", true).expect("Layer 29 scrolled into view"); + let drop = target + vec2(0.0, ROW_MEDIUM * 0.4); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)], true); + short_frame(&mut app, &ctx, vec![button(drop, false)], true); + let names = layer_names(&app); + assert_eq!(names.len(), 31); + assert_eq!((names[28].as_str(), names[30].as_str()), ("Layer 28", "Layer 29"), "{names:?}"); + assert!(names[29].starts_with("Layer 2"), "the copy, below Layer 29: {names:?}"); + assert_eq!(names[2], "Layer 2", "the original stays"); +} + +#[test] +fn the_list_scrolls_only_for_rows_held_over_it() { + let mut app = thirty_layers(); + let ctx = egui::Context::default(); + let (rows, view) = short_frame(&mut app, &ctx, vec![], false); + // The pointer in the bottom band with no button down: nothing scrolls. + let edge = egui::pos2(150.0, view.bottom() - 3.0); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)], false); + for _ in 0..20 { + assert_eq!(short_frame(&mut app, &ctx, vec![], false).0, rows, "hovering scrolls nothing"); + } + // A row held in the bottom band beside the list (right of its view): nothing scrolls, and + // the release there moves nothing. + let before = layer_names(&app); + let grab = rows["Layer 30"]; + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)], false); + short_frame(&mut app, &ctx, vec![button(grab, true)], false); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab + vec2(0.0, 6.0))], false); + let beside = egui::pos2(view.right() + 2.0, view.bottom() - 3.0); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(beside)], false); + // (Layer 30's dimmed copy follows the pointer, so another row is compared.) + assert!(rows.contains_key("Layer 27")); + for _ in 0..20 { + assert_eq!(short_frame(&mut app, &ctx, vec![], false).0.get("Layer 27"), rows.get("Layer 27"), "held beside the list"); + } + short_frame(&mut app, &ctx, vec![button(beside, false)], false); + short_frame(&mut app, &ctx, vec![], false); + assert_eq!(layer_names(&app), before); + // The eye column dragged down into the band: a column drag, which scrolls nothing. + let eye = egui::pos2(12.0, grab.y); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(eye)], false); + short_frame(&mut app, &ctx, vec![button(eye, true)], false); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(eye + vec2(0.0, 6.0))], false); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(egui::pos2(12.0, view.bottom() - 3.0))], false); + for _ in 0..20 { + assert_eq!(short_frame(&mut app, &ctx, vec![], false).0, rows, "a column drag"); + } + short_frame(&mut app, &ctx, vec![button(egui::pos2(12.0, view.bottom() - 3.0), false)], false); +} + /// The centres of the bottom bar's buttons, right to left from under the right end of its top /// divider: Delete, New Layer, New Sublayer, Make/Release Clipping Mask, Locate Object. fn bar_buttons(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 78ce76da32..cb62803a04 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -49,8 +49,6 @@ const LIST_VIEW: &str = "library-list-view"; const BAR: f32 = 42.0; /// The least height the list takes. const MIN_LIST: f32 = 140.0; -/// How near the list's top or bottom edge a drag scrolls it. -const EDGE: f32 = 28.0; /// The current library: its id and a copy of it (the panel menu acts on it after reading). fn current(app: &VectorcraftApp) -> Option<(String, Library)> { @@ -311,7 +309,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }); if items.grab.is_some() { - scroll_at_edges(ui); + super::scroll_at_edges(ui); } }); out.inner_rect @@ -658,22 +656,6 @@ fn no_group_strip(ui: &mut Ui) { ui.add_space(6.0); } -/// While something is dragged near the top or bottom edge of the scrolled list (`ui`: its -/// contents), scroll that way, faster nearer the edge. -fn scroll_at_edges(ui: &mut Ui) { - let Some(pos) = ui.ctx().pointer_hover_pos() else { return }; - let view = ui.clip_rect(); - if !view.x_range().contains(pos.x) { - return; - } - let speed = |depth: f32| if (0.0..EDGE).contains(&depth) { 2.0 + 10.0 * (1.0 - depth / EDGE) } else { 0.0 }; - let delta = speed(pos.y - view.top()) - speed(view.bottom() - pos.y); - if delta != 0.0 { - ui.scroll_with_delta(vec2(0.0, delta)); - ui.ctx().request_repaint(); - } -} - /// The drag in progress held over a section of the list (`sections`, seen through `clip`), away /// from the items that take one: an item goes into that section's group (the ungrouped section: /// out of its group), and something new is added there, the section outlined; a group goes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..83d10986bc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -510,7 +510,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons and Skill Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | -| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | +| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | | Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | | File formats | 6 | 85% | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | @@ -832,6 +832,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). - In the Layers panel only the primary mouse button drags. A drag with the right or middle button on a row, a guide row, the selection square, the eye or lock column or a target circle moves, copies, hides, locks and transfers nothing and records no undo step, and a right-click still opens the row's menu (`panels::layers` test `only_the_primary_button_drags_rows_guides_art_columns_and_appearances`). + - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge, and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view` and `the_list_scrolls_only_for_rows_held_over_it`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. - A floating panel's OS window hides while a tool group's flyout or the All Tools drawer is open in the main window, as it does under a modal dialog or a menu, and shows again when the flyout or the drawer closes (#5813; `a_tool_flyout_hides_the_palette_windows_until_it_closes`). - On the desktop a floating panel in an OS window stores the monitor it is on and reopens there at the next launch. When that monitor is no longer connected, the panel opens on the main window's monitor at the same offset (#5582). Outside macOS, a desktop whose monitors have different scale factors keeps opening floating panels on the main window's monitor. Test: `panel_docking::native_tests::a_floating_panel_reopens_on_the_monitor_where_it_was_left`. From 3990c748bdf68a9c6dd6eddecb49f4dbda889ea8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:29:55 -0800 Subject: [PATCH 12/28] Toolbars: toolbars made with New Toolbar dock along the window's edges A toolbar made with New Toolbar now docks in a lane along the window's left or right edge (on the left, right of the Tools panel docked there). Dropping its title bar on an edge docks it, with the target lit while the title bar is dragged over it; dragging it out of its lane floats it under the pointer, and Escape or losing the window's focus during the drag puts it back. The title bar's context menu has Dock to Left, Dock to Right and Float Toolbar. - Toolbars docked at one edge stack from the top, each with an equal share of the lane's height, and the lane is as wide as its widest toolbar. A lane too short for its stack wraps it into more columns, up to half the width beside it; past that the toolbars show only their title bars, a lone toolbar included, and a column too short for those scrolls with the mouse wheel. - With Keep Tools Beside the Canvas on and Tools docked on the left, the left lane is laid out inside the canvas panel right of Tools, and the canvas keeps room for one column of it and its 200 points. - A release in the frame the pointer leaves the lane floats the toolbar with its corner where the drag put it. - window.toolbar.dock {name, side?, order?} and window.toolbar.float {name, x?, y?} do the same from the control protocol; bad params are errors and change nothing. window.toolbar.list reports floating, side and order. - CustomToolbar keeps dock (place in the edge's stack) and dock_right; both default, so toolbars saved before load floating. Workspaces and preferences keep the placement; New Toolbar still starts floating, a copy floats, and deleting a docked toolbar closes up its stack. - Dock to Left, Dock to Right, Dock Toolbar and Float Toolbar have rows in every catalog. Part of #1759 --- crates/mcp/src/ui_catalog.rs | 19 +- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/input.rs | 1 + crates/ui-egui/src/custom_toolbars.rs | 1053 +++++++++++++++++++++- crates/ui-egui/src/edit_toolbar/tests.rs | 5 +- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/menus/ui_commands.rs | 19 +- crates/ui-egui/src/panel_docking.rs | 5 +- crates/ui-egui/src/state.rs | 13 +- crates/ui-egui/src/toolbar.rs | 2 + crates/ui-egui/src/tools_float.rs | 9 +- docs/control-protocol.md | 5 +- docs/gaps.md | 5 +- docs/mcp.md | 37 + docs/target-app-parity.md | 1 + 41 files changed, 1249 insertions(+), 35 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 342feb568c..bfea75d60a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -563,7 +563,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name: string} delete the toolbar made with New Toolbar called `name`, and the groups torn off it, from the current workspace, as Manage Toolbars' trash can does", ), - ("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"), + ( + "window.toolbar.dock", + "Dock Toolbar", + "", + "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}", + ), + ( + "window.toolbar.float", + "Float Toolbar", + "", + "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}", + ), + ( + "window.toolbar.list", + "List Toolbars", + "", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( "window.pathfinder.compoundShapes", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 67e67ac444..60d9b61027 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -599,6 +599,8 @@ impl VectorcraftApp { // Toolbar too. toolbar::show_custom(self, ui.ctx()); } + // The lanes along the window's edges where toolbars made with New Toolbar dock. + crate::custom_toolbars::lanes(self, ui); panels::library_panel::tidy(self); // The canvas and the panels: one docking layout. Tab hides the panels but not the canvas. egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui)); diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 29baa37d23..95f719d08b 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -16,6 +16,7 @@ impl VectorcraftApp { native_menu::run(self, ctx); if self.fonts_ready { tools_float::cancel_move_on_escape(self, ctx); + crate::custom_toolbars::cancel_move_on_escape(self, ctx); shortcuts::handle(self, ctx); } // A Copy taken in this UI phase (an egui copy event, or a command it runs) is published in diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index f356f18b68..2b4618048a 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -8,6 +8,17 @@ //! item shows or hides it, and is kept with the workspace it was made in (`Workspace::toolbars`). //! Window › Toolbars › Manage Toolbars (also in the drawer's menu) renames, copies and deletes them. //! +//! A toolbar docks in a lane along the window's left or right edge (on the left, right of the Tools +//! panel docked there or beside the canvas), when its title bar is dropped on the edge (lit up while it is dragged), or with +//! Dock to Left and Dock to Right in its title bar's context menu (`window.toolbar.dock`). Several +//! toolbars docked at one edge stack from the top in the order they docked, each with its share of +//! the lane's height, and the lane is as wide as its widest toolbar (a lane too short for its +//! stack wraps it into more columns, up to half the width beside it, and past that the toolbars +//! show only their title bars, which the mouse wheel scrolls through when even they do not fit, so +//! none covers another). Dragging a docked toolbar's +//! title bar out of it floats it under the pointer, as Float Toolbar does where it floated last +//! (`window.toolbar.float`); Escape during the drag puts it back. These are VectorCraft's own rules. +//! //! Behavior from the public documentation: //! (Create and manage toolbars: New Toolbar //! from Window › Toolbars or the drawer's flyout menu, a name and OK make a blank toolbar, its Edit @@ -41,6 +52,14 @@ const GRIP: f32 = 14.0; const TITLE_BUTTON: f32 = 12.0; /// Where the first toolbar made floats, right of the Tools panel; the next ones go lower. const NEW_AT: [f32; 2] = [96.0, 120.0]; +/// The space around each toolbar docked in a lane, and between two of them. +const LANE_GAP: f32 = 6.0; +/// Width of the strip along the window's edge where a dropped title bar docks its toolbar, while +/// that edge's lane is narrower or empty. +const ZONE: f32 = 48.0; +/// Points the pointer travels from its press before a drop docks (a click on the title bar of a +/// toolbar floating near the edge doesn't dock it). +const TRAVEL: f32 = 4.0; /// A toolbar's name without leading and trailing spaces, in lowercase. Names with the same key are /// the same name: lookups, the check that a name is free, sanitizing and each toolbar's area @@ -105,6 +124,8 @@ pub(crate) fn create(ui: &mut UiState, name: &str) -> Result { slots: vec![], shown: true, pos, + dock: None, + dock_right: false, slot_tool: Default::default(), double: false, floating: vec![], @@ -113,6 +134,95 @@ pub(crate) fn create(ui: &mut UiState, name: &str) -> Result { Ok(name.to_string()) } +/// Number the toolbars docked at each edge 0, 1, 2… from the top, in their order (in the list's +/// order where two have the same place). +fn renumber(bars: &mut [CustomToolbar]) { + for right in [false, true] { + let mut on: Vec<(Option, usize)> = + bars.iter().enumerate().filter(|(_, b)| b.dock.is_some() && b.dock_right == right).map(|(k, b)| (b.dock, k)).collect(); + on.sort_unstable(); + for (n, (_, k)) in on.into_iter().enumerate() { + if let Some(b) = bars.get_mut(k) { + b.dock = Some(n as u32); + } + } + } +} + +/// Dock the toolbar at `k` at the right edge or the left, at place `at` of that edge's stack (none +/// or past the end: at the end); the toolbars from that place down move down one. Returns its place. +fn dock_at(bars: &mut [CustomToolbar], k: usize, right: bool, at: Option) -> u32 { + if let Some(b) = bars.get_mut(k) { + b.dock = None; + } + renumber(bars); + let n = bars.iter().filter(|b| b.dock.is_some() && b.dock_right == right).count() as u32; + let at = at.map_or(n, |at| at.min(n)); + for b in bars.iter_mut().filter(|b| b.dock_right == right) { + if let Some(o) = b.dock.as_mut() + && *o >= at + { + *o += 1; + } + } + if let Some(b) = bars.get_mut(k) { + b.dock = Some(at); + b.dock_right = right; + } + at +} + +/// Where the toolbar is: `{toolbar, floating, side, order, pos}`, the edge it docks at (while it +/// floats, the edge it docked at last), its place in that edge's stack while docked (else null) and +/// where it floats (while docked, where it floated last). +fn placement(bar: &CustomToolbar) -> Value { + let side = if bar.dock_right { "right" } else { "left" }; + json!({ "toolbar": bar.name, "floating": bar.dock.is_none(), "side": side, "order": bar.dock, "pos": bar.pos }) +} + +/// The toolbars that show docked at the right edge or the left, by index, from the top. +fn docked(ui: &UiState, right: bool) -> Vec { + let mut on: Vec<(Option, usize)> = ui + .custom_toolbars + .iter() + .enumerate() + .filter(|(_, b)| b.shown && b.dock.is_some() && b.dock_right == right) + .map(|(k, b)| (b.dock, k)) + .collect(); + on.sort_unstable(); + on.into_iter().map(|(_, k)| k).collect() +} + +/// Width of `bar` inside its border: one column of tool buttons, or two. +fn bar_width(bar: &CustomToolbar) -> f32 { + WIDTH + if bar.double { BUTTON } else { 0.0 } +} + +/// The least height a docked toolbar draws at: its border, its title bar and the gap under it, the +/// least height its tools scroll in (`egui::ScrollArea`'s default `min_scrolled_height`, 64 points) +/// and its bottom margin. +const DOCKED_LEAST: f32 = 2.0 + GRIP + 4.0 + 64.0 + 4.0; + +/// The columns a lane `height` points tall lays `n` docked toolbars out in, at most `most` of them, +/// and the most toolbars each column holds: one column while each toolbar gets at least +/// [`DOCKED_LEAST`] points of the lane's height, else as few more columns as give every toolbar +/// that much, so none covers another. With `most` columns too few for that, the toolbars spread +/// evenly over `most` columns, and those with less than [`DOCKED_LEAST`] points show only their +/// title bars ([`docked_places`]). +fn lane_columns(n: usize, height: f32, most: usize) -> (usize, usize) { + let fit = ((height - LANE_GAP) / (DOCKED_LEAST + LANE_GAP)).floor(); + let fit = if fit.is_finite() && fit >= 1.0 { fit as usize } else { 1 }; + let per = n.div_ceil(n.div_ceil(fit).clamp(1, most.max(1))).max(1); + (n.div_ceil(per).max(1), per) +} + +/// The most columns of toolbars at most `widest` points wide inside their borders that `width` +/// points hold with [`LANE_GAP`] around each: at least one. +fn most_columns(width: f32, widest: f32) -> usize { + let most = ((width - LANE_GAP) / (widest.max(1.0) + LANE_GAP) + 1e-3).floor(); + if most.is_finite() && most >= 1.0 { most as usize } else { 1 } +} + /// Toolbar `name`, shown after Tab hid the toolbars, shows alone, as Window › Tools shows the /// Tools panel: the other toolbars Tab hid are turned off, and the next Tab hides it. fn show_alone_after_tab(ui: &mut UiState, name: &str) { @@ -193,6 +303,8 @@ pub(crate) fn duplicate(ui: &mut UiState, name: Option<&str>) -> Result, name: &str) let k = index(ui, name)?; close_popups(ui, ctx, name, None); ui.custom_toolbars.remove(k); + renumber(&mut ui.custom_toolbars); Ok(()) } /// Keep named toolbars, each name once whatever its case and at most [`MAX_NAME`] characters, of /// known tools, each once in its toolbar, at a position that is a number, with one strip per group -/// torn off them, and each group's tool chosen last only when the group holds it (a hand-edited -/// preferences file or workspace). +/// torn off them, each group's tool chosen last only when the group holds it, and the docked ones +/// numbered 0, 1, 2… at each edge (a hand-edited preferences file or workspace). pub(crate) fn sanitize(bars: &mut Vec) { let mut names = std::collections::BTreeSet::new(); bars.retain_mut(|b| { @@ -237,6 +350,7 @@ pub(crate) fn sanitize(bars: &mut Vec) { !b.name.is_empty() && b.name.chars().count() <= MAX_NAME && names.insert(key(&b.name)) }); bars.truncate(MAX); + renumber(bars); } /// Keep the strips torn off `bar` whose group it still holds, each with the group's tools as they @@ -306,11 +420,54 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option (|| { + let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?; + let k = index(&app.ui, name)?; + let bar = app.ui.custom_toolbars.get(k).ok_or_else(|| format!("no toolbar named `{name}`"))?; + // Docking: at the edge it docked at last unless `side` says which. + let right = match p.get("side") { + None | Some(Value::Null) => bar.dock_right, + // `Start` and `End`, as panels take them, too. + Some(Value::String(s)) if s.eq_ignore_ascii_case("left") || s.eq_ignore_ascii_case("start") => false, + Some(Value::String(s)) if s.eq_ignore_ascii_case("right") || s.eq_ignore_ascii_case("end") => true, + Some(Value::String(s)) => return Err(format!("side is left or right, not `{s}`")), + Some(v) => return Err(format!("side is left or right, not `{v}`")), + }; + let others = app.ui.custom_toolbars.iter().enumerate().filter(|&(i, b)| i != k && b.dock.is_some() && b.dock_right == right).count(); + let at = match p.get("order") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64().filter(|&n| n <= others as u64) { + Some(n) => Some(n as u32), + None => return Err(format!("order is a whole number from 0 to {others}, not `{v}`")), + }, + }; + // Docked at that edge already, with no place asked for, it stays where it is. + if !(bar.dock.is_some() && bar.dock_right == right && at.is_none()) { + dock_at(&mut app.ui.custom_toolbars, k, right, at); + } + app.ui.custom_toolbars.get(k).map(placement).ok_or_else(|| format!("no toolbar named `{name}`")) + })(), + "window.toolbar.float" => (|| { + let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?; + let k = index(&app.ui, name)?; + let at = crate::tools_float::position(p)?; + if let Some(b) = app.ui.custom_toolbars.get_mut(k) { + b.dock = None; + if let Some(at) = at { + b.pos = [at.x, at.y]; + } + } + renumber(&mut app.ui.custom_toolbars); + app.ui.custom_toolbars.get(k).map(placement).ok_or_else(|| format!("no toolbar named `{name}`")) + })(), "window.toolbar.list" => Ok(json!( app.ui .custom_toolbars .iter() - .map(|b| json!({"name": b.name, "shown": b.shown, "double": b.double, "slots": b.slots})) + .map(|b| { + let side = if b.dock_right { "right" } else { "left" }; + json!({"name": b.name, "shown": b.shown, "double": b.double, "slots": b.slots, "floating": b.dock.is_none(), "side": side, "order": b.dock}) + }) .collect::>() )), _ => return None, @@ -563,17 +720,268 @@ enum Action { Hide(String), /// The title bar's double arrow: two columns (true) or one. Columns(String, bool), + /// Dock to Left (false) or Dock to Right (true) in the title bar's context menu. + Dock(String, bool), + /// Float Toolbar in the title bar's context menu. + Float(String), } -/// The toolbars made with New Toolbar that show, each floating where its title bar was dragged: the -/// title bar's × hides it and its double arrow lays the tools out in one column or two; then its -/// tool buttons (a group's flyout opens as the Tools panel's do), the + button whose menu adds and -/// removes tools, and the ••• button that opens the All Tools drawer beside it. +/// The lane along the window's right edge (true) or left edge where docked toolbars show, as last +/// laid out; removed while it is empty. +fn lane_id(right: bool) -> egui::Id { + egui::Id::unique(("custom-toolbar-lane", right)) +} + +/// Where a title bar dropped docks its toolbar at the right edge (true) or the left, as last laid +/// out. +fn zone_id(right: bool) -> egui::Id { + egui::Id::unique(("custom-toolbar-zone", right)) +} + +/// A drag of a toolbar's title bar in progress: the toolbar, where the press began and how far that +/// is from the toolbar's corner, where the toolbar was before the drag (to put it back on Escape) +/// and whether Escape put it back. +#[derive(Clone, Debug)] +struct Move { + name: String, + from: egui::Pos2, + grab: egui::Vec2, + dock: Option, + right: bool, + pos: [f32; 2], + cancelled: bool, +} + +fn move_id() -> egui::Id { + egui::Id::unique("custom-toolbar-move") +} + +/// The lanes along the window's left and right edges where the docked toolbars that show are drawn, +/// each as wide as its widest toolbar with [`LANE_GAP`] either side (times the columns of +/// [`lane_columns`] when the lane is too short for one, at most half the width left for the lane), +/// and the targets where a title +/// bar dropped docks its toolbar: from the window's edge across the lane, or across a strip +/// [`ZONE`] points wide when the lane is narrower or empty, and on the left across the Tools panel +/// docked there too. Laid out before the canvas and the panels, which take the space left, except +/// the left lane while Tools is docked beside the canvas ([`left_lane_beside_canvas`]). A lane +/// laid out anew draws again, since its toolbars were placed by the lane of the frame before. +pub(crate) fn lanes(app: &VectorcraftApp, ui: &mut egui::Ui) { + for right in [false, true] { + if right || !left_lane_beside_canvas(&app.ui) { + let (edge, room) = (ui.ctx().content_rect(), ui.available_rect_before_wrap().width() / 2.0); + lane(app, ui, right, edge, room); + } + } +} + +/// The width the canvas panel keeps for the left lane while it stands beside the canvas +/// ([`left_lane_beside_canvas`]): one column of its widest toolbar, none while no docked toolbar +/// shows there. +pub(crate) fn beside_canvas_reserve(ui: &UiState) -> f32 { + if !left_lane_beside_canvas(ui) || ui.tab_hid.is_some() { + return 0.0; + } + let widest = docked(ui, false).iter().filter_map(|&k| ui.custom_toolbars.get(k)).map(bar_width).fold(0.0, f32::max); + if widest > 0.0 { widest + 2.0 * LANE_GAP } else { 0.0 } +} + +/// With Keep Tools Beside the Canvas on and Tools docked on the left, Tools draws inside the canvas +/// panel, right of the panels docked on the left, and the left lane goes right of it there +/// ([`lane_beside_canvas`]). +pub(crate) fn left_lane_beside_canvas(ui: &UiState) -> bool { + ui.tools_beside_canvas && ui.toolbar && ui.screen_mode < 3 && ui.toolbar_pos.is_none() && !ui.toolbar_right +} + +/// The left lane inside the canvas panel, right of the Tools panel docked beside the canvas +/// (`toolbar::show_beside_canvas`, after Tools). Its target reaches from the canvas's left edge, +/// across Tools, over the lane. It wraps into more columns only as far as the canvas keeps its +/// least width, 200 points (`panel_docking`'s canvas limits, which add [`beside_canvas_reserve`]). +pub(crate) fn lane_beside_canvas(app: &VectorcraftApp, ui: &mut egui::Ui) { + if left_lane_beside_canvas(&app.ui) { + let avail = ui.available_rect_before_wrap(); + let tools = ui.ctx().data(|d| d.get_temp::(crate::toolbar::docked_rect_id())); + let edge = tools.map_or(avail, |t| t.union(avail)); + lane(app, ui, false, edge, (avail.width() / 2.0).min(avail.width() - 200.0)); + } +} + +/// The lane at the right edge (true) or the left of `ui`'s space, at most `room` points wide unless +/// one column is wider, and its target, which reaches out to `edge`'s side. +fn lane(app: &VectorcraftApp, ui: &mut egui::Ui, right: bool, edge: egui::Rect, room: f32) { + let ctx = ui.ctx().clone(); + let shown = app.ui.tab_hid.is_none() && app.ui.screen_mode < 3; + let on = if shown { docked(&app.ui, right) } else { vec![] }; + let widest = on.iter().filter_map(|&k| app.ui.custom_toolbars.get(k)).map(bar_width).fold(0.0, f32::max); + let avail = ui.available_rect_before_wrap(); + let most = most_columns(room, widest); + let cols = lane_columns(on.len(), avail.height(), most).0 as f32; + let width = if widest > 0.0 { cols * widest + (cols - 1.0) * LANE_GAP } else { 0.0 }; + let reach = (width + 2.0 * LANE_GAP).max(ZONE); + let zone = if right { + egui::Rect::from_min_max(pos2(avail.right() - reach, avail.top()), pos2(edge.right(), avail.bottom())) + } else { + egui::Rect::from_min_max(pos2(edge.left(), avail.top()), pos2(avail.left() + reach, avail.bottom())) + }; + let lane = (width > 0.0).then(|| { + let panel = if right { egui::Panel::right("custom-toolbar-lane-right") } else { egui::Panel::left("custom-toolbar-lane-left") }; + panel.resizable(false).exact_size(width + 2.0 * LANE_GAP).frame(egui::Frame::NONE).show(ui, |_| {}).response.rect + }); + if ctx.data(|d| d.get_temp::(lane_id(right))) != lane { + ctx.request_repaint(); + } + ctx.data_mut(|d| { + d.insert_temp(zone_id(right), zone); + match lane { + Some(lane) => { + d.insert_temp(lane_id(right), lane); + } + None => d.remove::(lane_id(right)), + } + }); +} + +/// Where each docked toolbar that shows is drawn, by index: its top-left corner and the most height +/// it takes, and whether it shows only its title bar. Each lane stacks its toolbars from the top in +/// their order, each with an equal share of its column's height; a toolbar shorter than its share +/// leaves the rest to the ones below it. A lane too short for one column wraps its stack into the +/// columns of [`lane_columns`], left to right, as many as the lane is wide enough for, so every +/// toolbar's title bar and tools stay in view; when even those columns give a toolbar less than +/// [`DOCKED_LEAST`] points, the toolbars of that column show only their title bars, which still +/// float or dock them. When a column is too short for even their title bars, it shows as many as +/// fit and the mouse wheel over it scrolls through the rest; those scrolled out of view have no +/// corner. Every toolbar stays inside the lane. A toolbar docked since the lanes were last laid +/// out is not drawn until they are. +fn docked_places(ui: &UiState, ctx: &egui::Context) -> Vec<(usize, Option, f32, bool)> { + let mut out = vec![]; + // The least height a toolbar takes: its title bar, its border and its bottom margin. + let least = GRIP + LANE_GAP; + for right in [false, true] { + let Some(lane) = ctx.data(|d| d.get_temp::(lane_id(right))) else { continue }; + let on = docked(ui, right); + let widest = on.iter().filter_map(|&k| ui.custom_toolbars.get(k)).map(bar_width).fold(0.0, f32::max); + let (cols, per) = lane_columns(on.len(), lane.height(), most_columns(lane.width(), widest)); + let pitch = (lane.width() - LANE_GAP) / cols as f32; + for (c, column) in on.chunks(per).enumerate() { + let middle = lane.left() + LANE_GAP / 2.0 + pitch * (c as f32 + 0.5); + // More than even their title bars fit: the column shows as many as fit, and the wheel + // over the column scrolls through the others, one toolbar a notch. + let fits = ((lane.height() - LANE_GAP) / (least + LANE_GAP) + 1e-3).floor().max(1.0) as usize; + let column = if column.len() > fits { + let id = lane_id(right).with(("first", c)); + let left = lane.left() + LANE_GAP / 2.0 + pitch * c as f32; + let strip = egui::Rect::from_x_y_ranges(left..=left + pitch, lane.y_range()); + let notch = ctx.input(|i| { + let over = i.pointer.hover_pos().is_some_and(|p| strip.contains(p)); + let wheel = i.events.iter().filter_map(|e| if let egui::Event::MouseWheel { delta, .. } = e { Some(delta.y) } else { None }); + if over { wheel.sum::() } else { 0.0 } + }); + let mut first = ctx.data(|d| d.get_temp::(id)).unwrap_or(0); + if notch > 0.0 { + first = first.saturating_sub(1); + } else if notch < 0.0 { + first += 1; + } + let first = first.min(column.len() - fits); + ctx.data_mut(|d| d.insert_temp(id, first)); + let (before, rest) = column.split_at(first); + let (shown, after) = rest.split_at(fits); + out.extend(before.iter().chain(after).map(|&k| (k, None, 0.0, true))); + shown + } else { + column + }; + let n = column.len() as f32; + let share = (lane.height() - LANE_GAP * (n + 1.0)) / n.max(1.0); + // Too little height for its tools: the title bar alone. + let bare = share < DOCKED_LEAST; + let share = share.max(least); + let mut y = lane.top() + LANE_GAP; + for &k in column { + let Some(bar) = ui.custom_toolbars.get(k) else { continue }; + let drawn = ctx.memory(|m| m.area_rect(area_id(&bar.name))); + let w = drawn.map_or(bar_width(bar) + 2.0, |r| r.width()); + // Drawn last frame taller than its share (its tools scroll only above a least + // height), it moves up to end at the lane's bottom. + let tall = drawn.map_or(least, |r| r.height().max(least)); + let top = y.min(lane.bottom() - tall).max(lane.top()); + let room = share.min(lane.bottom() - top).max(least); + out.push((k, Some(pos2((middle - w / 2.0).round(), top)), room, bare)); + y = top + drawn.map_or(room, |r| r.height().min(room)) + LANE_GAP; + } + } + } + out +} + +/// The edge a title bar released at the pointer docks its toolbar at (true: the right), with the +/// target to light up: none until the pointer has moved [`TRAVEL`] points from the press at `from`. +fn drop_target(ctx: &egui::Context, from: egui::Pos2) -> Option<(egui::Rect, bool)> { + let at = ctx.input(|i| i.pointer.interact_pos()).filter(|at| at.distance(from) > TRAVEL)?; + [false, true].into_iter().find_map(|right| ctx.data(|d| d.get_temp::(zone_id(right))).filter(|z| z.contains(at)).map(|z| (z, right))) +} + +/// Put the toolbar being dragged back where the drag began; returns whether a drag was in progress. +fn cancel(ui: &mut UiState, ctx: &egui::Context) -> bool { + let Some(mut m) = ctx.data(|d| d.get_temp::(move_id())).filter(|m| !m.cancelled) else { return false }; + if let Ok(k) = index(ui, &m.name) { + match m.dock { + Some(at) => { + dock_at(&mut ui.custom_toolbars, k, m.right, Some(at)); + } + None => { + if let Some(b) = ui.custom_toolbars.get_mut(k) { + b.dock = None; + b.dock_right = m.right; + } + renumber(&mut ui.custom_toolbars); + } + } + if let Some(b) = ui.custom_toolbars.get_mut(k) { + b.pos = m.pos; + } + } + m.cancelled = true; + ctx.data_mut(|d| d.insert_temp(move_id(), m)); + true +} + +/// Escape while a toolbar's title bar is dragged puts the toolbar back where the drag began, and the +/// press runs no shortcut ([`crate::tools_float::escape_cancelled_move`]). +pub(crate) fn cancel_move_on_escape(app: &mut VectorcraftApp, ctx: &egui::Context) { + if ctx.input(|i| i.key_pressed(egui::Key::Escape)) && cancel(&mut app.ui, ctx) { + crate::tools_float::mark_escape_cancelled(ctx); + } +} + +/// Light up the target a title bar dropped now docks its toolbar at. +fn highlight(ctx: &egui::Context, zone: egui::Rect) { + let t = Tokens::get(ctx); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("custom-toolbar-drop"))); + painter.rect(zone.shrink(1.0), CornerRadius::same(2), t.accent.gamma_multiply(0.2), Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); +} + +/// The toolbars made with New Toolbar that show, each floating where its title bar was dragged or +/// docked in its edge's lane ([`lanes`]): the title bar's × hides it, its double arrow lays the +/// tools out in one column or two, and its context menu docks or floats it; then its tool buttons +/// (a group's flyout opens as the Tools panel's do), the + button whose menu adds and removes +/// tools, and the ••• button that opens the All Tools drawer beside it. pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + // A drag ends with the press, also for a toolbar hidden while it was dragged. + let end_move = || { + if !ctx.input(|i| i.pointer.primary_down()) { + ctx.data_mut(|d| d.remove::(move_id())); + } + }; // Tab hides them, also when Window › Tools shows the Tools panel again. if app.ui.tab_hid.is_some() || app.ui.custom_toolbars.iter().all(|b| !b.shown) { + end_move(); return; } + // Losing the window's focus puts a toolbar being dragged back, as Escape does. + if !ctx.input(|i| i.focused) { + cancel(&mut app.ui, ctx); + } + let places = docked_places(&app.ui, ctx); let t = Tokens::get(ctx); let screen = ctx.content_rect(); let active = app.session.tool_id(); @@ -592,11 +1000,27 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let id = area_id(&bar.name); let cols = if bar.double { 2 } else { 1 }; let width = WIDTH + BUTTON * (cols - 1) as f32; - // Kept on screen by its title bar and first tools: the rest scrolls. - let size = ctx.memory(|m| m.area_rect(id)).map_or(vec2(width, 60.0), |r| vec2(r.width(), r.height().min(160.0))); - let pos = crate::tools_float::clamp(bar.pos, size, screen); + // Docked: where its lane puts it, its tools scrolling in its share of the lane, or only its + // title bar when that share is too small for them. + let (pos, limit, bare) = if bar.dock.is_some() { + let Some(&(_, pos, share, bare)) = places.iter().find(|(i, ..)| *i == k) else { + // Docked since the lanes were laid out: drawn in the next frame. + ctx.request_repaint(); + continue; + }; + // Scrolled out of its column's view. + let Some(pos) = pos else { continue }; + (pos, share - LANE_GAP, bare) + } else { + // Kept on screen by its title bar and first tools: the rest scrolls. + let size = ctx.memory(|m| m.area_rect(id)).map_or(vec2(width, 60.0), |r| vec2(r.width(), r.height().min(160.0))); + let pos = crate::tools_float::clamp(bar.pos, size, screen); + (pos, screen.bottom() - pos.y - 12.0, false) + }; let edit_this = editing.as_deref() == Some(bar.name.as_str()); let mut moved = None; + // The title bar's drag this frame: started, going on, ended. + let mut drag = (false, false, false); let mut drops = None; // A Learn link locating a tool of this toolbar: its button, scrolled into view once. let locate = crate::panels::learn::locate::wanted(&app.ui, Some(&bar.name)); @@ -616,9 +1040,9 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).show(ctx, |ui| { crate::toolbar::flyout_frame(&t, false).inner_margin(egui::Margin { left: 0, right: 0, top: 0, bottom: 4 }).show(ui, |ui| { ui.set_width(width); - // The tools and the ••• button scroll when they don't fit in the window under the - // title bar. - ui.set_max_height(screen.bottom() - pos.y - 12.0); + // The tools and the ••• button scroll when they don't fit in the window (docked: in + // its share of the lane) under the title bar. + ui.set_max_height(limit); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let middle = ui.max_rect().center().x; // The title bar: × at its left end, the double arrow at its right end, and the grip @@ -641,14 +1065,31 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if aresp.on_hover_text(tl!("Toggle single/double column")).clicked() { actions.push(Action::Columns(bar.name.clone(), !bar.double)); } - // Not focusable (`Sense::drag()` is): only the pointer drags the grip, so Tab does not stop on it. - let gresp = ui.interact(grip, id.with("grip"), Sense::DRAG); + // Not focusable (`Sense::drag()` is): only the pointer drags the grip, so Tab does not + // stop on it. It senses clicks for its context menu. + let gresp = ui.interact(grip, id.with("grip"), Sense::CLICK | Sense::DRAG); for n in 0..3 { let y = grip.center().y - 2.0 + n as f32 * 2.0; let half = (grip.width() / 2.0 - 2.0).clamp(0.0, 8.0); ui.painter().line_segment([pos2(grip.center().x - half, y), pos2(grip.center().x + half, y)], Stroke::new(0.5, t.text_disabled)); } gresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &bar.name)); + // Its context menu: Dock to Left and Dock to Right, the edge it is docked at checked, + // and Float Toolbar while it is docked. + gresp.context_menu(|ui| { + for (right, label) in [(false, tl!("Dock to Left")), (true, tl!("Dock to Right"))] { + let here = bar.dock.is_some() && bar.dock_right == right; + if widgets::menu_item(ui, label, !here, here) { + actions.push(Action::Dock(bar.name.clone(), right)); + ui.close(); + } + } + if widgets::menu_item(ui, tl!("Float Toolbar"), bar.dock.is_some(), false) { + actions.push(Action::Float(bar.name.clone())); + ui.close(); + } + }); + drag = (gresp.drag_started(), gresp.dragged(), gresp.drag_stopped()); // Held where the press took it, from the toolbar's corner, while it is dragged. let grab = id.with("grab"); if gresp.dragged() { @@ -662,6 +1103,9 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.data_mut(|d| d.remove::(grab)); gresp.on_hover_cursor(egui::CursorIcon::Grab).on_hover_text(&bar.name); } + if bare { + return; + } // A gap keeps a press near the grip bar's lower edge on the bar. ui.add_space(4.0); let mut buttons: Vec<(usize, egui::Rect)> = vec![]; @@ -713,11 +1157,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { crate::edit_toolbar::toolbar_drop(app, ui, &buttons, cols, bounds, Some(&bar.name)); } }); - if let Some(p) = moved.filter(|p| p.x.is_finite() && p.y.is_finite()) - && let Some(b) = app.ui.custom_toolbars.get_mut(k) - { - b.pos = [p.x, p.y]; - } + drag_title_bar(app, ctx, k, drag, moved); // The button is marked when it shows the located tool, else the group's flyout opens on it; // a group torn off into a strip is marked there. if did_scroll { @@ -788,8 +1228,71 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { app.status(e); } } + Action::Dock(name, right) => { + if let Err(e) = app.run("window.toolbar.dock", json!({ "name": name, "side": if right { "right" } else { "left" } })) { + app.status(e); + } + } + Action::Float(name) => { + if let Err(e) = app.run("window.toolbar.float", json!({ "name": name })) { + app.status(e); + } + } } } + end_move(); +} + +/// The drag of the title bar of the toolbar at `k` this frame (`drag`: started, going on, ended), +/// with the pointer holding its corner at `moved`. A floating toolbar follows the pointer, and the +/// target under the pointer lights up; released there, it docks at the end of that edge's stack. A +/// docked toolbar stays in its lane until the pointer leaves the lane, and then floats under the +/// pointer, also when the press is released in the frame it leaves the lane. +/// After Escape, the rest of the drag moves nothing. +fn drag_title_bar(app: &mut VectorcraftApp, ctx: &egui::Context, k: usize, drag: (bool, bool, bool), moved: Option) { + let (started, dragging, stopped) = drag; + let Some(bar) = app.ui.custom_toolbars.get(k) else { return }; + if started && let Some(from) = ctx.input(|i| i.pointer.press_origin().or(i.pointer.interact_pos())) { + let grab = ctx.memory(|m| m.area_rect(area_id(&bar.name))).map_or(egui::Vec2::ZERO, |r| from - r.min); + let m = Move { name: bar.name.clone(), from, grab, dock: bar.dock, right: bar.dock_right, pos: bar.pos, cancelled: false }; + ctx.data_mut(|d| d.insert_temp(move_id(), m)); + } + let Some(m) = ctx.data(|d| d.get_temp::(move_id())).filter(|m| !m.cancelled && key(&m.name) == key(&bar.name)) else { + return; + }; + let from = m.from; + let mut docked = bar.dock.is_some(); + if docked && (dragging || stopped) { + let at = ctx.input(|i| i.pointer.interact_pos()); + // Where the pointer holds its corner; on the release frame, which reports no move, from + // where the press took it. + let corner = moved.or_else(|| at.map(|at| at - m.grab)).filter(|p| p.x.is_finite() && p.y.is_finite()); + let lane = ctx.data(|d| d.get_temp::(lane_id(bar.dock_right))).or_else(|| ctx.memory(|m| m.area_rect(area_id(&bar.name)))); + let inside = lane.zip(at).is_some_and(|(r, at)| r.contains(at)); + if !inside && let Some(p) = corner { + if let Some(b) = app.ui.custom_toolbars.get_mut(k) { + b.dock = None; + b.pos = [p.x, p.y]; + } + renumber(&mut app.ui.custom_toolbars); + docked = false; + } + } else if dragging + && let Some(p) = moved.filter(|p| p.x.is_finite() && p.y.is_finite()) + && let Some(b) = app.ui.custom_toolbars.get_mut(k) + { + b.pos = [p.x, p.y]; + } + if docked { + return; + } + let target = drop_target(ctx, from); + if dragging && let Some((zone, _)) = target { + highlight(ctx, zone); + } + if stopped && let Some((_, right)) = target { + dock_at(&mut app.ui.custom_toolbars, k, right, None); + } } /// What a toolbar's tool buttons need from the frame: the toolbar, the active tool, whether the @@ -970,10 +1473,8 @@ mod tests { let names: Vec<&str> = toolbars_menu(&app).into_iter().filter(|(_, id, _)| *id == "window.toolbar.custom").map(|(l, ..)| l).collect(); assert_eq!(names, ["Mine", "Toolbar 1"]); let list = app.run("window.toolbar.list", json!({})).unwrap(); - assert_eq!( - list, - json!([{"name": "Mine", "shown": true, "double": false, "slots": []}, {"name": "Toolbar 1", "shown": true, "double": false, "slots": []}]) - ); + let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "floating": true, "side": "left", "order": null}); + assert_eq!(list, json!([blank("Mine"), blank("Toolbar 1")])); } /// The New Toolbar dialog: a name typed in it and Enter make the toolbar; a name that is taken is @@ -1691,6 +2192,8 @@ mod tests { slots: slots.iter().map(|s| s.iter().map(|id| id.to_string()).collect()).collect(), shown: true, pos: [f32::NAN, 0.0], + dock: None, + dock_right: false, slot_tool: Default::default(), double: false, floating: ["pen", "nope", "pen"] @@ -1712,7 +2215,10 @@ mod tests { bars[0].slot_tool = chosen(&[("pen", "curvature"), ("curvature", "pen"), ("nope", "pen")]); bars[4].slot_tool = chosen(&[("pen", "curvature")]); bars[5].slot_tool = chosen(&[("pen", "curvature")]); + // Docked places with gaps and repeats, and one dropped with its toolbar, are numbered from 0. + (bars[0].dock, bars[1].dock, bars[4].dock, bars[5].dock) = (Some(7), Some(0), Some(7), Some(3)); sanitize(&mut bars); + assert_eq!(bars.iter().map(|b| b.dock).collect::>(), [Some(1), Some(2), Some(0)]); assert_eq!(bars.iter().map(|b| b.name.as_str()).collect::>(), ["A", "B", "C"], "a name past {MAX_NAME} characters goes too"); assert_eq!(bars[0].slot_tool, chosen(&[("pen", "curvature")])); assert!(bars[1].slot_tool.is_empty() && bars[2].slot_tool.is_empty(), "{:?} {:?}", bars[1].slot_tool, bars[2].slot_tool); @@ -1722,4 +2228,503 @@ mod tests { assert_eq!(bars[0].floating.iter().map(|f| f.tools.join(",")).collect::>(), ["pen,curvature"]); assert!(bars[1].floating.is_empty(), "B holds no group"); } + + /// Where the toolbar named `name` is: its place in its edge's stack (none: floating) and + /// whether that edge is the right one. + fn place(app: &VectorcraftApp, name: &str) -> (Option, bool) { + let b = find(&app.ui, name).unwrap(); + (b.dock, b.dock_right) + } + + /// `window.toolbar.dock` docks a toolbar at an edge, at the end of its stack or at the place + /// asked for, and `window.toolbar.float` floats it where it floated last or at x, y; bad params + /// change nothing. Hiding and renaming keep its place, a copy floats, and deleting closes the + /// stack up. The places are listed, and kept with the workspace and the preferences. + #[test] + fn toolbars_dock_and_float_by_their_commands() { + let mut app = app(); + app.run("window.workspace.new", json!({"name": "Drawing"})).unwrap(); + for name in ["A", "B", "C"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + assert_eq!(place(&app, "A"), (None, false), "New Toolbar floats"); + let a_pos = find(&app.ui, "A").unwrap().pos; + let r = app.run("window.toolbar.dock", json!({"name": "a"})).unwrap(); + assert_eq!(r, json!({"toolbar": "A", "floating": false, "side": "left", "order": 0, "pos": a_pos})); + app.run("window.toolbar.dock", json!({"name": "B", "side": "left"})).unwrap(); + app.run("window.toolbar.dock", json!({"name": "C", "side": "start", "order": 0})).unwrap(); + assert_eq!([place(&app, "C"), place(&app, "A"), place(&app, "B")], [(Some(0), false), (Some(1), false), (Some(2), false)]); + // Docked again at the edge it is docked at, it stays where it is. + app.run("window.toolbar.dock", json!({"name": "A"})).unwrap(); + assert_eq!(place(&app, "A"), (Some(1), false)); + app.run("window.toolbar.dock", json!({"name": "A", "order": 2})).unwrap(); + assert_eq!([place(&app, "C"), place(&app, "B"), place(&app, "A")], [(Some(0), false), (Some(1), false), (Some(2), false)]); + // Bad params are errors and change nothing. + let before = app.ui.custom_toolbars.clone(); + for p in [ + json!({"name": "A", "side": "top"}), + json!({"name": "A", "side": 1}), + json!({"name": "A", "order": 3}), + json!({"name": "A", "order": -1}), + json!({"name": "A", "order": 0.5}), + json!({"name": "A", "order": "1"}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.dock", p.clone()).is_err(), "{p}"); + } + for p in + [json!({"name": "A", "x": 10}), json!({"name": "A", "x": 1e7, "y": 0}), json!({"name": "A", "x": "1", "y": 2}), json!({"name": "Nope"})] + { + assert!(app.run("window.toolbar.float", p.clone()).is_err(), "{p}"); + } + assert_eq!(app.ui.custom_toolbars, before); + // At the right edge; the left edge's stack closes up. + let r = app.run("window.toolbar.dock", json!({"name": "A", "side": "RIGHT"})).unwrap(); + assert_eq!((&r["side"], &r["order"]), (&json!("right"), &json!(0))); + assert_eq!([place(&app, "C"), place(&app, "B")], [(Some(0), false), (Some(1), false)]); + // Floating where it floated last or at x, y; docked again at the edge it docked at last. + let r = app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!(r, json!({"toolbar": "A", "floating": true, "side": "right", "order": null, "pos": a_pos})); + app.run("window.toolbar.float", json!({"name": "A", "x": 300, "y": 200})).unwrap(); + assert_eq!(find(&app.ui, "A").unwrap().pos, [300.0, 200.0]); + assert_eq!(app.run("window.toolbar.dock", json!({"name": "A"})).unwrap()["side"], json!("right")); + // Hidden and renamed, it keeps its place; a copy floats; deleted, the stack closes up. + app.run("window.toolbar.custom", json!({"name": "C", "show": false})).unwrap(); + app.run("window.toolbar.rename", json!({"name": "C", "to": "Cee"})).unwrap(); + assert_eq!(place(&app, "Cee"), (Some(0), false)); + let copy = app.run("window.toolbar.duplicate", json!({"name": "B"})).unwrap(); + assert_eq!(place(&app, copy["toolbar"].as_str().unwrap()), (None, false)); + app.run("window.toolbar.delete", json!({"name": "Cee"})).unwrap(); + assert_eq!(place(&app, "B"), (Some(0), false)); + let list = app.run("window.toolbar.list", json!({})).unwrap(); + let rows: Vec<_> = list.as_array().unwrap().iter().map(|b| json!([b["name"], b["floating"], b["side"], b["order"]])).collect(); + assert_eq!(rows, [json!(["A", false, "right", 0]), json!(["B", false, "left", 0]), json!(["B Copy", true, "left", null])]); + // Kept with the workspace and the preferences. + let kept = app.ui.custom_toolbars.clone(); + app.run("window.workspace", json!({"name": "Essentials"})).unwrap(); + app.run("window.workspace", json!({"name": "Drawing"})).unwrap(); + assert_eq!(app.ui.custom_toolbars, kept); + let prefs: UiState = serde_json::from_slice(&serde_json::to_vec(&app.ui).unwrap()).unwrap(); + assert_eq!(prefs.sanitized().custom_toolbars, kept); + // Saved before toolbars docked, a toolbar floats. + let mut old = serde_json::to_value(&kept[0]).unwrap(); + let fields = old.as_object_mut().unwrap(); + assert!(fields.remove("dock").is_some() && fields.remove("dock_right").is_some()); + let old: CustomToolbar = serde_json::from_value(old).unwrap(); + assert_eq!((old.dock, old.dock_right), (None, false)); + } + + /// Docked toolbars show in lanes along the window's edges, the left one right of the Tools + /// panel: stacked from the top, centered, each in its share of the lane, the lane as wide as its + /// widest toolbar and gone while none shows. The canvas and the panels take the space left. + #[test] + fn docked_toolbars_stack_in_lanes_along_the_window_edges() { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + for name in ["A", "B", "R"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + for tool in vectorcraft_tools::TOOL_GROUPS.iter().flat_map(|g| g.iter()).take(30) { + app.run("toolbar.addTool", json!({"tool": tool.id, "toolbar": "A"})).unwrap(); + } + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "B"})).unwrap(); + let mut time = 0.0; + let mut frames = |app: &mut VectorcraftApp| { + for _ in 0..4 { + time += 0.05; + window_frame(app, &ctx, time, 600.0); + } + }; + frames(&mut app); + let rect = |name: &str| ctx.memory(|m| m.area_rect(area_id(name))).unwrap(); + let lane = |right: bool| ctx.data(|d| d.get_temp::(lane_id(right))); + assert!(lane(false).is_none() && lane(true).is_none(), "no lane while every toolbar floats"); + for (name, side) in [("A", "left"), ("B", "left"), ("R", "right")] { + app.run("window.toolbar.dock", json!({ "name": name, "side": side })).unwrap(); + } + frames(&mut app); + let tools = ctx.data(|d| d.get_temp::(crate::toolbar::docked_rect_id())).unwrap(); + let (left, right) = (lane(false).unwrap(), lane(true).unwrap()); + let (a, b, r) = (rect("A"), rect("B"), rect("R")); + assert!((left.left() - tools.right()).abs() < 1.0 && (left.width() - WIDTH - 2.0 * LANE_GAP).abs() < 0.5, "{left:?} {tools:?}"); + assert!(left.contains_rect(a) && left.contains_rect(b) && right.contains_rect(r), "{left:?} {a:?} {b:?} {right:?} {r:?}"); + assert!((right.right() - 1200.0).abs() < 0.5, "{right:?}"); + assert!(b.top() >= a.bottom() && (a.center().x - left.center().x).abs() < 1.0 && (b.center().x - a.center().x).abs() < 1.0, "{a:?} {b:?}"); + // A's 30 tools scroll in its half of the lane. + assert!(a.height() <= left.height() / 2.0, "{a:?} {left:?}"); + // The canvas ends left of the right lane. + let canvas_right = ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_right_id())).unwrap().right(); + assert!(canvas_right <= right.left() + 0.5, "{canvas_right} {right:?}"); + // Two columns widen the lane, and the toolbar stays docked. + app.run("window.toolbarColumns", json!({"toolbar": "B", "double": true})).unwrap(); + frames(&mut app); + assert!((lane(false).unwrap().width() - WIDTH - BUTTON - 2.0 * LANE_GAP).abs() < 0.5); + assert!(lane(false).unwrap().contains_rect(rect("B")) && place(&app, "B") == (Some(1), false)); + // Hidden, it keeps its place, and an empty lane goes. + app.run("window.toolbar.custom", json!({"name": "R", "show": false})).unwrap(); + frames(&mut app); + assert!(lane(true).is_none() && !drawn(&ctx, area_id("R"), egui::Order::Middle) && place(&app, "R") == (Some(0), true)); + // Tab hides the lanes with the toolbars. + app.run("window.dock", json!({})).unwrap(); + frames(&mut app); + assert!(lane(false).is_none() && !drawn(&ctx, area_id("A"), egui::Order::Middle)); + } + + /// With Keep Tools Beside the Canvas on, the left lane stands right of Tools, which stands right + /// of the panels docked on the left, and its target covers Tools and the lane, not the panels. In a + /// narrow window the lane leaves the canvas its least width of 200 points. With the setting off + /// again, the lane goes back to the window's edge, right of Tools. + #[test] + fn the_left_lane_follows_tools_docked_beside_the_canvas() { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + app.run("window.toolbar.new", json!({"name": "A"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "A"})).unwrap(); + app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); + app.run("window.toolsBesideCanvas", json!({"on": true})).unwrap(); + app.run("window.toolbar.dock", json!({"name": "A", "side": "left"})).unwrap(); + let mut time = 0.0; + let mut frames = |app: &mut VectorcraftApp, size: egui::Vec2| { + for _ in 0..6 { + time += 0.05; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + let raw = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + } + }; + frames(&mut app, vec2(1200.0, 600.0)); + let tools = || ctx.data(|d| d.get_temp::(crate::toolbar::docked_rect_id())).unwrap(); + let lane = || ctx.data(|d| d.get_temp::(lane_id(false))).unwrap(); + let zone = ctx.data(|d| d.get_temp::(zone_id(false))).unwrap(); + let a = ctx.memory(|m| m.area_rect(area_id("A"))).unwrap(); + assert!(tools().left() > 100.0, "Tools stands right of the left dock: {:?}", tools()); + assert!((lane().left() - tools().right()).abs() < 1.0, "{:?} {:?}", lane(), tools()); + assert!(lane().contains_rect(a), "{a:?} {:?}", lane()); + assert!(zone.contains(tools().center()) && zone.right() >= lane().right() - 0.5, "{zone:?}"); + assert!(!zone.contains(pos2(4.0, tools().center().y)), "the left dock is not a target: {zone:?}"); + // In a narrow, short window, a stack that wraps leaves the canvas its 200 points. + for k in 0..12 { + let name = format!("T{k}"); + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": name})).unwrap(); + app.run("window.toolbar.dock", json!({ "name": name, "side": "left" })).unwrap(); + } + frames(&mut app, vec2(700.0, 320.0)); + // The canvas panel's right edge, and the canvas drawn right of the lane. + let right = ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_right_id())).unwrap().right(); + let canvas = app.canvas_rect.unwrap(); + assert!(right - lane().right() >= 199.5 && canvas.left() >= lane().right() - 0.5, "{right} {canvas:?} {:?} {:?}", lane(), tools()); + app.run("window.toolsBesideCanvas", json!({"on": false})).unwrap(); + frames(&mut app, vec2(1200.0, 600.0)); + assert!(tools().left() < 1.0 && (lane().left() - tools().right()).abs() < 1.0, "{:?} {:?}", lane(), tools()); + } + + /// More docked toolbars than a short lane holds in one column wrap into more columns: each stays + /// inside the lane with its title bar, and none covers another. With more than half the window's + /// width of columns needed (60 toolbars), the lane stops at half the width and the toolbars show + /// only their title bars, still each in view. + #[test] + fn a_short_lane_keeps_every_docked_toolbar_inside_it() { + for count in [12, 60] { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + let names: Vec = (0..count).map(|k| format!("T{k}")).collect(); + for name in &names { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": name})).unwrap(); + app.run("window.toolbar.dock", json!({ "name": name, "side": "right" })).unwrap(); + } + for k in 0..6 { + window_frame(&mut app, &ctx, 0.05 * f64::from(k + 1), 320.0); + } + let lane = ctx.data(|d| d.get_temp::(lane_id(true))).unwrap(); + let rects: Vec = names.iter().map(|name| ctx.memory(|m| m.area_rect(area_id(name))).unwrap()).collect(); + for (name, r) in names.iter().zip(&rects) { + assert!(lane.expand(0.5).contains_rect(*r), "{count}: {name} {r:?} {lane:?}"); + assert!(r.height() >= GRIP, "{count}: {name} {r:?}"); + } + for (i, a) in rects.iter().enumerate() { + for (j, b) in rects.iter().enumerate().skip(i + 1) { + assert!(a.intersect(*b).area() < 1.0, "{count}: {} {a:?} covers {} {b:?}", names[i], names[j]); + } + } + assert!(lane.width() > WIDTH + 2.0 * LANE_GAP + 1.0, "the stack wraps into more columns: {lane:?}"); + assert!(lane.width() <= 600.0, "{count}: the lane leaves the canvas at least half the window: {lane:?}"); + assert!((lane.right() - 1200.0).abs() < 0.5, "{lane:?}"); + let bare = rects.iter().all(|r| r.height() < DOCKED_LEAST - 1.0); + assert_eq!(bare, count == 60, "{count}: title bars alone only when the columns run out: {rects:?}"); + } + } + + /// A lone docked toolbar in a lane too short for its tools shows only its title bar, inside the + /// lane. + #[test] + fn a_lone_toolbar_in_a_short_lane_stays_inside_it() { + let mut short = 0; + for height in (120..=240).step_by(10) { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + app.run("window.toolbar.new", json!({"name": "A"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "A"})).unwrap(); + app.run("window.toolbar.dock", json!({"name": "A", "side": "right"})).unwrap(); + for k in 0..6 { + window_frame(&mut app, &ctx, 0.05 * f64::from(k + 1), height as f32); + } + let lane = ctx.data(|d| d.get_temp::(lane_id(true))).unwrap(); + if lane.height() >= DOCKED_LEAST + 2.0 * LANE_GAP { + continue; + } + short += 1; + let a = ctx.memory(|m| m.area_rect(area_id("A"))).unwrap(); + assert!(lane.expand(0.5).contains_rect(a), "{height}: {a:?} {lane:?}"); + assert!(a.height() >= GRIP, "{height}: the title bar shows: {a:?}"); + } + assert!(short > 0, "some window heights leave a lane shorter than one toolbar"); + } + + /// A column too short for even its toolbars' title bars shows as many as fit, none covering + /// another, and the mouse wheel over it scrolls through the rest, one toolbar a notch. + #[test] + fn a_column_too_short_for_its_title_bars_scrolls() { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + let names: Vec = (0..64).map(|k| format!("T{k}")).collect(); + for name in &names { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + app.run("window.toolbar.dock", json!({ "name": name, "side": "right" })).unwrap(); + } + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 200.0)); + let raw = egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }; + ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }) + .textures_delta + .clear(); + }; + for _ in 0..6 { + frame(&mut app, vec![]); + } + let shown = + |ctx: &egui::Context| -> Vec { (0..names.len()).filter(|&k| drawn(ctx, area_id(&names[k]), egui::Order::Middle)).collect() }; + let lane = ctx.data(|d| d.get_temp::(lane_id(true))).unwrap(); + let before = shown(&ctx); + assert!(!before.is_empty() && before.len() < names.len(), "{before:?} {lane:?}"); + let rects: Vec = before.iter().map(|&k| ctx.memory(|m| m.area_rect(area_id(&names[k]))).unwrap()).collect(); + for (i, a) in rects.iter().enumerate() { + assert!(lane.expand(0.5).contains_rect(*a), "{a:?} {lane:?}"); + for b in rects.iter().skip(i + 1) { + assert!(a.intersect(*b).area() < 1.0, "{a:?} covers {b:?}"); + } + } + assert!(before.contains(&0)); + // The wheel over the first column shows the next toolbar of that column. + let at = pos2(lane.left() + LANE_GAP + WIDTH / 2.0, lane.center().y); + let wheel = |dy: f32| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + frame(&mut app, vec![egui::Event::PointerMoved(at), wheel(-1.0)]); + frame(&mut app, vec![]); + let after = shown(&ctx); + assert!(!after.contains(&0) && after.len() == before.len(), "{before:?} {after:?}"); + frame(&mut app, vec![egui::Event::PointerMoved(at), wheel(1.0)]); + frame(&mut app, vec![]); + assert_eq!(shown(&ctx), before, "the wheel back shows the first again"); + } + + /// A lane holds one column while each docked toolbar gets [`DOCKED_LEAST`] points, and as few + /// more columns as give each that much, the toolbars spread evenly over them, up to the most + /// columns the lane may take. + #[test] + fn short_lanes_wrap_their_stack_into_columns() { + let tall = 2.0 * (DOCKED_LEAST + LANE_GAP) + LANE_GAP; + assert_eq!(lane_columns(0, 500.0, 8), (1, 1)); + assert_eq!(lane_columns(2, tall, 8), (1, 2)); + assert_eq!(lane_columns(3, tall, 8), (2, 2)); + assert_eq!(lane_columns(5, tall, 8), (3, 2)); + assert_eq!(lane_columns(4, 10.0, 8), (4, 1), "a lane shorter than one toolbar puts each in its own column"); + assert_eq!(lane_columns(3, f32::NAN, 8), (3, 1)); + assert_eq!(lane_columns(9, tall, 2), (2, 5), "at most the columns allowed"); + assert_eq!(lane_columns(9, tall, 0), (1, 9)); + assert_eq!(most_columns(3.0 * WIDTH + 4.0 * LANE_GAP, WIDTH), 3); + assert_eq!(most_columns(10.0, WIDTH), 1); + assert_eq!(most_columns(f32::NAN, WIDTH), 1); + } + + /// The frame that docks a toolbar lays its lane out after the toolbars are drawn, so it asks for + /// the next frame at once, which draws the toolbar in the lane, without other input. + #[test] + fn a_new_lane_draws_its_toolbar_in_the_next_frame() { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp| { + time += 0.05; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 600.0)); + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + out.viewport_output.values().map(|v| v.repaint_delay).min().unwrap_or(std::time::Duration::MAX) + }; + for _ in 0..4 { + frame(&mut app); + } + app.run("window.toolbar.dock", json!({"name": "Mine"})).unwrap(); + assert_eq!(frame(&mut app), std::time::Duration::ZERO, "the frame that lays the new lane out asks for another"); + frame(&mut app); + let lane = ctx.data(|d| d.get_temp::(lane_id(false))).unwrap(); + assert!(lane.contains_rect(ctx.memory(|m| m.area_rect(area_id("Mine"))).unwrap())); + } + + /// A docked toolbar dragged inside its lane stays docked. A toolbar's title bar dropped on the + /// window's edge docks it there; dragged out of its lane, + /// it floats under the pointer; Escape during the drag puts it back; a click near the edge does + /// not dock it. The title bar's context menu docks and floats it. + #[test] + fn a_title_bar_dropped_on_an_edge_docks_the_toolbar() { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 800.0)); + let raw = egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + // The texts drawn, with where each is. + let texts = out.shapes.iter().filter_map(|c| { + if let egui::Shape::Text(t) = &c.shape { Some((t.galley.text().to_string(), t.visual_bounding_rect())) } else { None } + }); + texts.collect::>() + }; + let button = |pos, pressed, button| egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() }; + let primary = egui::PointerButton::Primary; + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + for _ in 0..3 { + frame(&mut app, vec![]); + } + // Docked and dragged down its lane, past its own bottom, it stays docked. + app.run("window.toolbar.dock", json!({"name": "Mine", "side": "left"})).unwrap(); + for _ in 0..3 { + frame(&mut app, vec![]); + } + let r = ctx.memory(|m| m.area_rect(area_id("Mine"))).unwrap(); + let lane = ctx.data(|d| d.get_temp::(lane_id(false))).unwrap(); + let (from, below) = (pos2(r.center().x, r.top() + 1.0 + GRIP / 2.0), pos2(lane.center().x, lane.bottom() - 20.0)); + assert!(!r.contains(below), "{r:?} {lane:?}"); + frame(&mut app, vec![egui::Event::PointerMoved(from), button(from, true, primary)]); + for k in 1..=6 { + frame(&mut app, vec![egui::Event::PointerMoved(from + (below - from) * (k as f32 / 6.0))]); + assert_eq!(place(&app, "Mine"), (Some(0), false), "a drag inside the lane keeps it docked, step {k}"); + } + frame(&mut app, vec![button(below, false, primary)]); + app.run("window.toolbar.float", json!({"name": "Mine"})).unwrap(); + for _ in 0..3 { + frame(&mut app, vec![]); + } + // A press on the title bar's grip, moved in steps to `to` (`cut` after the step it names), + // then released there. + let mut drag = |app: &mut VectorcraftApp, from: egui::Pos2, to: egui::Pos2, cut: Option| { + frame(app, vec![egui::Event::PointerMoved(from), button(from, true, primary)]); + for k in 1..=6 { + let mut events = vec![egui::Event::PointerMoved(from + (to - from) * (k as f32 / 6.0))]; + if cut == Some(k) { + events.push(escape.clone()); + } + frame(app, events); + } + frame(app, vec![button(to, false, primary)]); + frame(app, vec![]); + frame(app, vec![]); + }; + let grip = |ctx: &egui::Context| { + let r = ctx.memory(|m| m.area_rect(area_id("Mine"))).unwrap(); + pos2(r.center().x, r.top() + 1.0 + GRIP / 2.0) + }; + // Dropped on the window's left edge, it docks there. + drag(&mut app, grip(&ctx), pos2(20.0, 400.0), None); + assert_eq!(place(&app, "Mine"), (Some(0), false)); + let lane = ctx.data(|d| d.get_temp::(lane_id(false))).unwrap(); + assert!(lane.contains_rect(ctx.memory(|m| m.area_rect(area_id("Mine"))).unwrap())); + // Escape while it is dragged out of the lane puts it back in its place. + drag(&mut app, grip(&ctx), pos2(600.0, 300.0), Some(4)); + assert_eq!(place(&app, "Mine"), (Some(0), false), "Escape keeps it docked"); + // Dragged out of the lane, it floats under the pointer. + drag(&mut app, grip(&ctx), pos2(600.0, 300.0), None); + assert_eq!(place(&app, "Mine"), (None, false)); + assert!(ctx.memory(|m| m.area_rect(area_id("Mine"))).unwrap().contains(pos2(600.0, 300.0))); + // Escape while it is dragged to the right edge leaves it floating where it was. + let at = find(&app.ui, "Mine").unwrap().pos; + drag(&mut app, grip(&ctx), pos2(1195.0, 400.0), Some(5)); + assert_eq!((place(&app, "Mine"), find(&app.ui, "Mine").unwrap().pos), ((None, false), at)); + // Dropped on the right edge, it docks there. + drag(&mut app, grip(&ctx), pos2(1195.0, 400.0), None); + assert_eq!(place(&app, "Mine"), (Some(0), true)); + // Floating over the edge, a click on its title bar does not dock it. + app.run("window.toolbar.float", json!({"name": "Mine", "x": 2, "y": 300})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let at = grip(&ctx); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true, primary)]); + frame(&mut app, vec![button(at, false, primary)]); + frame(&mut app, vec![]); + assert_eq!(place(&app, "Mine"), (None, true)); + // The title bar's context menu: Dock to Left docks it, and Float Toolbar floats it again. + for (item, after) in [("Dock to Left", (Some(0), false)), ("Float Toolbar", (None, false))] { + let at = grip(&ctx); + let secondary = egui::PointerButton::Secondary; + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true, secondary)]); + frame(&mut app, vec![button(at, false, secondary)]); + let texts = frame(&mut app, vec![]); + let found = texts.iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == item); + let at = found.unwrap_or_else(|| panic!("no {item} in {texts:?}")).1.center(); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true, primary)]); + frame(&mut app, vec![button(at, false, primary)]); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + assert_eq!(place(&app, "Mine"), after, "after {item}"); + } + // Docked, and released in the frame the pointer leaves the lane, it floats there. + app.run("window.toolbar.dock", json!({"name": "Mine"})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let at = grip(&ctx); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true, primary)]); + frame(&mut app, vec![egui::Event::PointerMoved(at + vec2(0.0, 8.0))]); + assert_eq!(place(&app, "Mine"), (Some(0), false), "still in its lane"); + let out = pos2(600.0, 300.0); + frame(&mut app, vec![egui::Event::PointerMoved(out), button(out, false, primary)]); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + assert_eq!(place(&app, "Mine"), (None, false), "released outside its lane"); + assert!(ctx.memory(|m| m.area_rect(area_id("Mine"))).unwrap().contains(out)); + } } diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index e47561094e..cac6338418 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -508,7 +508,10 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { assert_eq!(slots(&app), shipped, "the Tools panel's toolbar is untouched"); assert!(!app.ui.tools_drawer, "no drawer opened"); let list = app.run("window.toolbar.list", json!({})).unwrap(); - assert_eq!(list, json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]]}])); + assert_eq!( + list, + json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]], "floating": true, "side": "left", "order": null}]) + ); // A second tool goes after the first. let shown = open(&mut app, 19.0); click(&mut app, &ctx, 20.0, items(&shown, "Magic Wand Tool")[0].0); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..cf3dec273d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4052,6 +4052,10 @@ axis Both И двете Dock Panel Закотвен панел Dock to Top Закотвяне горе Dock to Bottom Закотвяне долу + Dock to Left Закотвяне вляво + Dock to Right Закотвяне вдясно + Dock Toolbar Закотвяне на лентата с инструменти + Float Toolbar Плаваща лента с инструменти Control Bar Options Опции на контролната лента Tool Options Опции за инструмент Object Options Опции за обект diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..1c6efe09b4 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -908,6 +908,10 @@ Dock Panel Usidri panel Dock to Top Usidri na vrh Dock to Bottom Usidri na dno + Dock to Left Usidri lijevo + Dock to Right Usidri desno + Dock Toolbar Usidri traku s alatima + Float Toolbar Odvoji traku s alatima Control Bar Options Opcije kontrolne trake Tool Options Opcije alata Object Options Opcije objekta diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..af4e171e47 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1247,6 +1247,10 @@ antiAlias Sharp Nítid Dock Panel Acobla el panell Dock to Top Acobla a dalt Dock to Bottom Acobla a baix + Dock to Left Acobla a l’esquerra + Dock to Right Acobla a la dreta + Dock Toolbar Acobla la barra d’eines + Float Toolbar Flota la barra d’eines Control Bar Options Opcions de la barra de control Tool Options Opcions de l’eina Object Options Opcions de l’objecte diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..4431c720e5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -923,6 +923,10 @@ Dock Panel Ukotvit panel Dock to Top Ukotvit nahoru Dock to Bottom Ukotvit dolů + Dock to Left Ukotvit vlevo + Dock to Right Ukotvit vpravo + Dock Toolbar Ukotvit panel nástrojů + Float Toolbar Plovoucí panel nástrojů Control Bar Options Možnosti ovládacího panelu Tool Options Možnosti nástroje Object Options Možnosti objektu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..06b554631e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -853,6 +853,10 @@ Dock Panel Dok panel Dock to Top Dok øverst Dock to Bottom Dok nederst + Dock to Left Dok til venstre + Dock to Right Dok til højre + Dock Toolbar Dok værktøjslinjen + Float Toolbar Flydende værktøjslinje Control Bar Options Indstillinger for kontrollinjen Tool Options Værktøjsindstillinger Object Options Objektindstillinger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..0b5f1887b4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4074,6 +4074,10 @@ theme Appearance Erscheinungsbild Dock Panel Bedienfeld andocken Dock to Top Oben andocken Dock to Bottom Unten andocken + Dock to Left Links andocken + Dock to Right Rechts andocken + Dock Toolbar Werkzeugleiste andocken + Float Toolbar Werkzeugleiste ablösen Control Bar Options Optionen der Steuerungsleiste Tool Options Werkzeugoptionen Object Options Objektoptionen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..ee7e173604 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2257,6 +2257,10 @@ axis Both Και τα δύο Dock Panel Αγκύρωση πάνελ Dock to Top Αγκύρωση επάνω Dock to Bottom Αγκύρωση κάτω + Dock to Left Αγκύρωση αριστερά + Dock to Right Αγκύρωση δεξιά + Dock Toolbar Αγκύρωση γραμμής εργαλείων + Float Toolbar Αιωρούμενη γραμμή εργαλείων Control Bar Options Επιλογές γραμμής ελέγχου Tool Options Επιλογές εργαλείου Object Options Επιλογές αντικειμένου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..08c8ab13fb 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4150,6 +4150,10 @@ axis Both Ambos Dock Panel Anclar panel Dock to Top Anclar arriba Dock to Bottom Anclar abajo + Dock to Left Anclar a la izquierda + Dock to Right Anclar a la derecha + Dock Toolbar Anclar barra de herramientas + Float Toolbar Hacer flotar la barra de herramientas Control Bar Options Opciones de la barra de control Tool Options Opciones de herramienta Object Options Opciones de objeto diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..bafb620fc0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -911,6 +911,10 @@ Dock Panel Telakoi paneeli Dock to Top Telakoi ylös Dock to Bottom Telakoi alas + Dock to Left Telakoi vasemmalle + Dock to Right Telakoi oikealle + Dock Toolbar Telakoi työkalurivi + Float Toolbar Kelluta työkalurivi Control Bar Options Ohjauspalkin asetukset Tool Options Työkalun asetukset Object Options Objektin asetukset diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..3cd787bd97 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4139,6 +4139,10 @@ axis Both Les deux Dock Panel Ancrer le panneau Dock to Top Ancrer en haut Dock to Bottom Ancrer en bas + Dock to Left Ancrer à gauche + Dock to Right Ancrer à droite + Dock Toolbar Ancrer la barre d’outils + Float Toolbar Rendre la barre d’outils flottante Control Bar Options Options de la barre de contrôle Tool Options Options de l’outil Object Options Options de l’objet diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..cdc1de5b8a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1386,6 +1386,10 @@ antiAlias Sharp शार्प Dock Panel पैनल डॉक करें Dock to Top ऊपर डॉक करें Dock to Bottom नीचे डॉक करें + Dock to Left बाईं ओर डॉक करें + Dock to Right दाईं ओर डॉक करें + Dock Toolbar टूलबार डॉक करें + Float Toolbar टूलबार फ़्लोट करें Control Bar Options नियंत्रण बार ऑप्शन्स Tool Options टूल ऑप्शन्स Object Options ऑब्जेक्ट ऑप्शन्स diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..5bb08d52fc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1114,6 +1114,10 @@ font-technology Variable Változó Dock Panel Panel dokkolása Dock to Top Dokkolás felülre Dock to Bottom Dokkolás alulra + Dock to Left Dokkolás balra + Dock to Right Dokkolás jobbra + Dock Toolbar Eszköztár dokkolása + Float Toolbar Eszköztár lebegtetése Control Bar Options Vezérlősáv beállításai Tool Options Eszközbeállítások Object Options Objektumbeállítások diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..e1499a5821 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -853,6 +853,10 @@ Dock Panel Tambatkan panel Dock to Top Tambatkan ke atas Dock to Bottom Tambatkan ke bawah + Dock to Left Tambatkan ke kiri + Dock to Right Tambatkan ke kanan + Dock Toolbar Tambatkan bilah alat + Float Toolbar Mengambangkan bilah alat Control Bar Options Opsi bilah kontrol Tool Options Opsi alat Object Options Opsi objek diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..8f01c8358a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4201,6 +4201,10 @@ axis Both Entrambi Dock Panel Ancora pannello Dock to Top Ancora in alto Dock to Bottom Ancora in basso + Dock to Left Ancora a sinistra + Dock to Right Ancora a destra + Dock Toolbar Ancora barra degli strumenti + Float Toolbar Rendi mobile barra degli strumenti Control Bar Options Opzioni barra di controllo Tool Options Opzioni strumento Object Options Opzioni oggetto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..817d515334 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4143,6 +4143,10 @@ axis Both 両方 Dock Panel パネルをドッキング Dock to Top 上部にドッキング Dock to Bottom 下部にドッキング + Dock to Left 左側にドッキング + Dock to Right 右側にドッキング + Dock Toolbar ツールバーをドッキング + Float Toolbar ツールバーをフローティング Control Bar Options コントロールバーオプション Tool Options ツールオプション Object Options オブジェクトオプション diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..93ff9f8e96 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -816,6 +816,10 @@ Dock Panel პანელის მიმაგრება Dock to Top ზემოთ მიმაგრება Dock to Bottom ქვემოთ მიმაგრება + Dock to Left მარცხნივ მიმაგრება + Dock to Right მარჯვნივ მიმაგრება + Dock Toolbar ხელსაწყოთა ზოლის მიმაგრება + Float Toolbar მცურავი ხელსაწყოთა ზოლი Control Bar Options მართვის ზოლის პარამეტრები Tool Options ხელსაწყოს პარამეტრები Object Options ობიექტის პარამეტრები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..5132cf1484 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4127,6 +4127,10 @@ axis Both 양쪽 Dock Panel 패널 고정 Dock to Top 위쪽에 고정 Dock to Bottom 아래쪽에 고정 + Dock to Left 왼쪽에 고정 + Dock to Right 오른쪽에 고정 + Dock Toolbar 도구 막대 고정 + Float Toolbar 도구 막대 분리 Control Bar Options 컨트롤 막대 옵션 Tool Options 도구 옵션 Object Options 개체 옵션 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..8f3c2da6b9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -867,6 +867,10 @@ Dock Panel Paneel dokken Dock to Top Bovenaan dokken Dock to Bottom Onderaan dokken + Dock to Left Links dokken + Dock to Right Rechts dokken + Dock Toolbar Werkbalk dokken + Float Toolbar Werkbalk laten zweven Control Bar Options Opties voor bedieningsbalk Tool Options Gereedschapsopties Object Options Objectopties diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..049de20359 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -868,6 +868,10 @@ Dock Panel Zadokuj panel Dock to Top Zadokuj u góry Dock to Bottom Zadokuj u dołu + Dock to Left Zadokuj po lewej + Dock to Right Zadokuj po prawej + Dock Toolbar Zadokuj pasek narzędzi + Float Toolbar Odepnij pasek narzędzi Control Bar Options Opcje paska sterowania Tool Options Opcje narzędzia Object Options Opcje obiektu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..83ffa09c26 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3379,6 +3379,10 @@ imageTrace Outline Contorno Dock Panel Encaixar Painel Dock to Top Encaixar na Parte Superior Dock to Bottom Encaixar na Parte Inferior + Dock to Left Encaixar à Esquerda + Dock to Right Encaixar à Direita + Dock Toolbar Encaixar Barra de Ferramentas + Float Toolbar Flutuar Barra de Ferramentas Control Bar Options Opções da Barra de Controle Tool Options Opções de Ferramenta Object Options Opções de Objeto diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..76d1ce271b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4187,6 +4187,10 @@ axis Both Оба Dock Panel Прикрепить панель Dock to Top Прикрепить сверху Dock to Bottom Прикрепить снизу + Dock to Left Прикрепить слева + Dock to Right Прикрепить справа + Dock Toolbar Прикрепить панель инструментов + Float Toolbar Сделать панель инструментов плавающей Control Bar Options Параметры панели управления Tool Options Параметры инструмента Object Options Параметры объекта diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..0eec252189 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4066,6 +4066,10 @@ axis Both Båda Dock Panel Docka panel Dock to Top Docka överst Dock to Bottom Docka nederst + Dock to Left Docka till vänster + Dock to Right Docka till höger + Dock Toolbar Docka verktygsfältet + Float Toolbar Gör verktygsfältet flytande Control Bar Options Alternativ för kontrollfältet Tool Options Verktygsalternativ Object Options Objektalternativ diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..a30a5547af 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3950,6 +3950,10 @@ axis Both Her İkisi Dock Panel Bağlantı İstasyonu Paneli Dock to Top Üste yerleştir Dock to Bottom Alta yerleştir + Dock to Left Sola yerleştir + Dock to Right Sağa yerleştir + Dock Toolbar Araç çubuğunu yerleştir + Float Toolbar Araç Çubuğunu Yüzer Yap Control Bar Options Kontrol Çubuğu Seçenekleri Tool Options Araç Seçenekleri Object Options Nesne Seçenekleri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..31e42b581e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4190,6 +4190,10 @@ axis Both Обидві Dock Panel Прикріпити панель Dock to Top Прикріпити вгорі Dock to Bottom Прикріпити внизу + Dock to Left Прикріпити ліворуч + Dock to Right Прикріпити праворуч + Dock Toolbar Прикріпити панель інструментів + Float Toolbar Від’єднати панель інструментів Control Bar Options Параметри панелі керування Tool Options Параметри інструменту Object Options Параметри об’єкта diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..70e11365c5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1012,6 +1012,10 @@ font-technology Variable Biến thiên Dock Panel Neo bảng Dock to Top Neo lên trên Dock to Bottom Neo xuống dưới + Dock to Left Neo sang trái + Dock to Right Neo sang phải + Dock Toolbar Neo thanh công cụ + Float Toolbar Thả nổi thanh công cụ Control Bar Options Tùy chọn thanh điều khiển Tool Options Tùy chọn công cụ Object Options Tùy chọn đối tượng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..ed292747a2 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5437,6 +5437,10 @@ axis Both 两者 Dock Panel 停放面板 Dock to Top 停放到顶部 Dock to Bottom 停放到底部 + Dock to Left 停放到左侧 + Dock to Right 停放到右侧 + Dock Toolbar 停放工具栏 + Float Toolbar 浮动工具栏 Control Bar Options 控制栏选项 Tool Options 工具选项 Object Options 对象选项 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..24abfce36f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5266,6 +5266,10 @@ axis Both 兩者 Dock Panel 停駐面板 Dock to Top 停駐到頂部 Dock to Bottom 停駐到底部 + Dock to Left 停駐到左側 + Dock to Right 停駐到右側 + Dock Toolbar 停駐工具列 + Float Toolbar 浮動工具列 Control Bar Options 控制列選項 Tool Options 工具選項 Object Options 物件選項 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 20a2c58314..cd3a391793 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -564,7 +564,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name: string} delete the toolbar made with New Toolbar called `name`, and the groups torn off it, from the current workspace, as Manage Toolbars' trash can does", ), - ("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"), + ( + "window.toolbar.dock", + "Dock Toolbar", + "", + "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}", + ), + ( + "window.toolbar.float", + "Float Toolbar", + "", + "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}", + ), + ( + "window.toolbar.list", + "List Toolbars", + "", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( "window.pathfinder.compoundShapes", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index cc72f74b77..e22dcd9cac 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1435,8 +1435,9 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } fn limits(&self, id: &String) -> craft_ui::docking::PanelLimits { - let min = - if id == CANVAS { egui::vec2(200.0 + crate::toolbar::docked_width(&self.app.ui), 120.0) } else { egui::vec2(PANEL_MIN_WIDTH, 80.0) }; + // The canvas keeps room for Tools and the lane of toolbars docked beside it. + let beside = crate::toolbar::docked_width(&self.app.ui) + crate::custom_toolbars::beside_canvas_reserve(&self.app.ui); + let min = if id == CANVAS { egui::vec2(200.0 + beside, 120.0) } else { egui::vec2(PANEL_MIN_WIDTH, 80.0) }; craft_ui::docking::PanelLimits { min, ..Default::default() } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f84b8f53b0..91fb21ac05 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -864,7 +864,8 @@ impl FloatingFlyout { } /// A toolbar made with Window › Toolbars › New Toolbar (`window.toolbar.new`): it floats on its -/// own, filled with tools from the All Tools drawer, and is kept with the workspace it was made in. +/// own or docks along the window's left or right edge, filled with tools from the All Tools drawer, +/// and is kept with the workspace it was made in. /// The groups torn off it are kept with it (`floating`), so the Tools panel's strips /// (`UiState::floating_flyouts`) hold none of them. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -877,8 +878,16 @@ pub struct CustomToolbar { /// It shows (Window › Toolbars › its name toggles it). #[serde(default = "yes")] pub shown: bool, - /// Top-left corner in screen points. + /// Top-left corner in screen points while it floats; while it is docked, where it floated last. pub pos: [f32; 2], + /// Its place in the stack of toolbars docked along one of the window's edges (0 at the top), + /// while it is docked there; none while it floats at `pos`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dock: Option, + /// It docks along the window's right edge, not the left: the edge it is docked at, or while it + /// floats the edge it docked at last. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub dock_right: bool, /// The tool each slot of several tools shows, chosen last (keyed by the slot's first tool). #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub slot_tool: std::collections::BTreeMap, diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index b1788e1e8a..90f5f74646 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -145,6 +145,8 @@ pub(crate) fn show_beside_canvas(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.toolbar_pos.is_none() && (app.ui.tools_beside_canvas || app.ui.toolbar_right) { show(app, ui); } + // The lane where toolbars made with New Toolbar dock on the left, right of Tools. + crate::custom_toolbars::lane_beside_canvas(app, ui); } /// Is the Tools panel docked on the right, between the canvas and the panels? diff --git a/crates/ui-egui/src/tools_float.rs b/crates/ui-egui/src/tools_float.rs index 0cc6433429..b5fb04d384 100644 --- a/crates/ui-egui/src/tools_float.rs +++ b/crates/ui-egui/src/tools_float.rs @@ -46,6 +46,13 @@ pub(crate) fn escape_cancelled_move(ctx: &egui::Context) -> bool { ctx.data(|d| d.get_temp::(escape_cancel_id())) == Some(ctx.cumulative_frame_nr_for(ctx.viewport_id())) } +/// This frame's Escape put a moved bar back ([`escape_cancelled_move`]): a toolbar made with New +/// Toolbar ([`crate::custom_toolbars::cancel_move_on_escape`]) as well as the Tools panel. +pub(crate) fn mark_escape_cancelled(ctx: &egui::Context) { + let frame = ctx.cumulative_frame_nr_for(ctx.viewport_id()); + ctx.data_mut(|d| d.insert_temp(escape_cancel_id(), frame)); +} + /// The strip along the canvas's left edge where the Tools panel docks while Keep Tools Beside the /// Canvas is on, as last laid out. pub(crate) fn tools_zone_id() -> Id { @@ -194,7 +201,7 @@ pub fn track(app: &mut VectorcraftApp, ctx: &egui::Context) { } /// The `x`, `y` params: a top-left corner in screen points, if given. -fn position(p: &Value) -> Result, String> { +pub(crate) fn position(p: &Value) -> Result, String> { let coord = |k: &str| match p.get(k) { None | Some(Value::Null) => Some(None), Some(v) => v.as_f64().filter(|f| f.abs() < 1e6).map(|f| Some(f as f32)), diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5694d9582d..1a0d5c7d7d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -417,7 +417,10 @@ button (Add Tool…) opens a menu of every tool under the drawer's headings: a c {tool, toolbar}`; the tools already in the toolbar are dimmed under their headings. The drawer has no Show section there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag, -two-column flag, top-left corner, the groups torn off it). They are kept with the workspace they were made in: +two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked). +`window.toolbar.dock {name, side?, order?}` docks a toolbar in the lane along the window's left or right edge, and +`window.toolbar.float {name, x?, y?}` floats it again; dropping its title bar on an edge or dragging it out of its +lane does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them. diff --git a/docs/gaps.md b/docs/gaps.md index d34956d4e0..cdb15df0bd 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -684,8 +684,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** custom document ruler origin (#1212): corner drag with preview, double-click reset to the active artboard, relative X/Y inputs and native save/reopen. - **Done:** View › Rulers › Change to Global / Artboard Rulers (`view.globalRulers`, Cmd+Alt+R): artboard rulers, a new document's, count from the active artboard, each artboard with its own zero point; rulers, X/Y fields and guide readouts follow the mode, which is saved with the document. Estimate unchanged. - **Done (#2849):** View › Rulers › Show Video Rulers (`view.videoRulers`): the rulers show and count the active artboard in video pixels from its top-left corner, a pixel as many points wide as the artboard's Video Ruler Pixel Aspect Ratio and one point tall ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)); Hide Video Rulers returns them to the General unit and the ruler origin. Shift-snapping a new guide to ruler ticks still uses the General unit's ticks. Estimate unchanged. -- **Partial:** custom toolbars (#1759): Window › Toolbars › New Toolbar makes them, kept with the workspace they - were made in, and Window › Toolbars › Manage Toolbars renames, copies and deletes them; docking them is missing. +- **Done:** custom toolbars (#1759): Window › Toolbars › New Toolbar makes them, kept with the workspace they + were made in, and Window › Toolbars › Manage Toolbars renames, copies and deletes them; they dock in lanes along + the window's left and right edges (`window.toolbar.dock`, `window.toolbar.float`). Inside the estimate below. - **Done (#1753):** a saved workspace keeps the width of the dock column. - **Done (#4135):** floating panels open in OS windows of their own on the desktop, so they can sit on another monitor; on the web and on Wayland they float inside the window. diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..13ad15ab4c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2672,6 +2672,43 @@ kept with the workspace, and built-in workspaces and workspaces saved without it {"name":"invoke_menu","arguments":{"command":"window.toolsBesideCanvas","params":{"on":true}}} ``` +## Docking toolbars made with New Toolbar + +A toolbar made with New Toolbar floats when it is made. `window.toolbar.dock {name, side?, order?}` (Dock to Left and +Dock to Right in the context menu of the toolbar's title bar, remote mode, `invoke_menu`) docks it in a lane along the +window's left or right edge. On the left, the lane is right of the Tools panel when the Tools panel is docked at the +window's edge. With Keep Tools Beside the Canvas on and the Tools panel docked on the left, the lane is right of the +Tools panel beside the canvas, and dropping a title bar on the Tools panel or on the lane docks the toolbar there. `side` is `left` or `right` (`start` and `end` also work); without it, the toolbar docks at the edge it +docked at last, or at the left the first time. Toolbars docked at one edge stack from the top. `order` is the +toolbar's place in that stack, 0 at the top, from 0 to the number of other toolbars docked there; without it, the +toolbar goes at the end, or stays where it is when it is already docked at that edge. Each toolbar takes an equal +share of the lane's height and its tools scroll in it, and the lane is as wide as its widest toolbar. When the lane +is too short to give each toolbar 88 points of height, the stack wraps into more columns, left to right, and the lane +widens, so no toolbar covers another. A lane takes at most half the width the canvas and panels would have (beside +the canvas, it also leaves the canvas at least 200 points, and the canvas keeps room for one column); when that +many columns still give a toolbar less than 88 points, the toolbars in those columns show only their title bars, which +still float, dock and show the context menu. A column too short for all of its title bars shows as many as fit, and +the mouse wheel over the column scrolls through the others, one toolbar per notch. +`window.toolbar.float {name, x?, y?}` (Float Toolbar in the same menu) floats it with its top-left corner at `x`, `y` +in screen points, or where it floated last when both are omitted. Both commands answer +`{toolbar, floating, side, order, pos}`: `side` is the edge the toolbar docks at (while it floats, the edge it docked +at last), `order` its place in that edge's stack (null while it floats) and `pos` where it floats (while it is docked, +where it floated last). A missing or unknown name, a `side` other than left or right, an `order` that is not a whole +number in range, or only one of `x` and `y` is an error and changes nothing. `window.toolbar.list` reports `floating`, +`side` and `order` for each toolbar. + +With the pointer, dropping a floating toolbar's title bar on the window's left or right edge, or on that edge's lane, +docks it at the end of that edge's stack; the target lights up while the title bar is dragged over it. Dragging a +docked toolbar's title bar out of its lane floats it under the pointer. Escape, or the window losing focus, during +the drag puts the toolbar back where it was. Hiding a docked toolbar keeps its place, renaming it keeps its place, a +copy made with Manage Toolbars' + floats, and deleting one closes up the stack. Placement is kept with the workspace. +Toolbars saved before docking existed load floating. The lanes, the edge targets and the stacking are VectorCraft's +own layout rules. + +```json +{"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} +``` + ## Learn panel Window › Learn and the Explore tutorials button beside the search icon at the right end of the app bar show and hide diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..7ee5253df3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -840,6 +840,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`). - A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`). - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). + - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - Window › Help Bar shows or hides the tool-help strip at the bottom of the window apart from the status bar (`window.helpBar`). Each setting is kept with the UI preferences and in saved workspaces, and Presentation Mode hides both bars. Layouts saved before the setting existed show the Help Bar where they show the status bar (`help_bar_toggle_is_independent_and_saved_in_workspaces`, `help_bar_and_status_bar_render_independently`, `legacy_help_bar_visibility_follows_each_layouts_status_bar`, `a_help_bar_setting_the_file_lacks_is_saved`). From ab75b67f852878f19c7cec2c94abeeb308565a17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:33:23 -0800 Subject: [PATCH 13/28] =?UTF-8?q?Simplify:=20the=20join=20at=20the=20start?= =?UTF-8?q?=20of=20a=20smoothed=20loop=20turns=20by=20at=20most=200.5?= =?UTF-8?q?=C2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A smoothed loop with no corner is refitted along one direction across its start. The first and the last fitted curve were each compared with that direction, so when both became lines, the two lines could turn by up to 1° where they meet at the loop's start. `refit_part` now compares the last curve of such a loop with the direction the loop's first segment leaves along. When the line would turn by more than 0.5° from it, the last piece stays a flat curve. Test: `simplify_keeps_the_join_at_the_start_of_a_smoothed_loop_smooth` (`crates/pathops/tests/it/ops.rs`). --- crates/pathops/src/edit.rs | 10 ++++++++-- crates/pathops/tests/it/ops.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 19089dfd2e..bc1d54cba9 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -329,12 +329,18 @@ fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, ends: Op // The fit may be `tol * 0.98` from the lines between the samples, those lines may be // `SAMPLE_GAP` of `tol` from the path, and the curve the test below turns into a line moves by up // to 1.5% of `tol`: 3/4 of how far its handles may be from the line. The fitted curves join - // smoothly, so a curve becomes a line only when the line keeps both of its joins smooth. + // smoothly, so a curve becomes a line only when the line keeps both of its joins smooth. The last + // curve of a loop fitted across its start leaves along the loop's first segment. let (t0, t1) = ends.map_or((start_tangent(&first.c), end_tangent(&last.c)), |d| (d, d)); let fitted = fit_cubics(&pts, t0, t1, tol * 0.98); + let from = result.len(); let mut arrive = t0; for (k, &c) in fitted.iter().enumerate() { - let leave = fitted.get(k + 1).map_or(t1, start_tangent); + let leave = match fitted.get(k + 1) { + Some(next) => start_tangent(next), + None if ends.is_some() => result.get(from).map_or(t1, |s| start_tangent(&s.c)), + None => t1, + }; let line = is_straight(&c, tol * 0.02) && line_keeps_joins(&c, arrive, leave); arrive = if line { unit(c.p3 - c.p0).unwrap_or(arrive) } else { end_tangent(&c) }; result.push(if line { Seg::line(c.p0, c.p3) } else { Seg { c, line } }); diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index d48e1c5dd8..93f6d4c29c 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -462,6 +462,32 @@ fn simplify_turns_a_curve_into_a_line_only_where_the_joins_stay_smooth() { assert!(!has_curves(&s), "{s:?}"); } +/// A smoothed loop with no corner is fitted across its start, and the join there also turns by at +/// most 0.5°. Each loop is a flat side that bends by 0.6° at the loop's start, closed by an arc of +/// `n` lines `height` tall, with `inner` anchors along each half of the side. +#[test] +fn simplify_keeps_the_join_at_the_start_of_a_smoothed_loop_smooth() { + for (half, height, n, inner, tolerance, smooth) in + [(40.0, 20.0, 8, 3, 2.5, 2.0), (80.0, 60.0, 8, 3, 5.0, 0.5), (160.0, 200.0, 24, 3, 10.0, 2.0), (160.0, 20.0, 24, 8, 10.0, 5.0)] + { + let rise = half * 0.3f64.to_radians().tan(); + let along = |i: i32| Point::new(half * f64::from(i) / f64::from(inner), -rise * f64::from(i.abs()) / f64::from(inner)); + let mut pts: Vec = (0..=inner).map(along).collect(); + pts.extend((1..n).map(|i| { + let a = f64::from(i) / f64::from(n) * PI; + Point::new(half * a.cos(), -rise - height * a.sin()) + })); + pts.extend((-inner..0).map(along)); + let path = PathData::single(SubPath::polyline(&pts, true)); + let s = simplify_with(&path, &SimplifyOptions { tolerance, corner_angle_deg: 179.0, smooth, ..Default::default() }); + let sp = &s.subpaths[0]; + assert!(sp.closed && sp.anchors.len() < pts.len(), "{tolerance} pt: {s:?}"); + assert!(sp.segment_is_line(0), "{tolerance} pt: the first segment is a curve: {s:?}"); + let turn = largest_join_turn(sp); + assert!(turn <= 0.5 + 1e-9, "{tolerance} pt: an anchor turns {turn}°: {s:?}"); + } +} + #[test] fn simplify_straight_lines_option() { let c = dense_circle(50.0, 200); From 7232875e9f9a5e9193f04e1b38ff3ce16a5842d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:53:01 -0800 Subject: [PATCH 14/28] Layers: rows held at the list's edge scroll it at the same speed at every frame rate A row held in the 28-point band at the list's top or bottom edge scrolled the list by a fixed distance each frame, so the list moved farther in the same time on a display that redraws more often. `scroll_at_edges` now scrolls by the time each frame took: 60 points a second at the band's inner side and 340 at the edge. A stalled frame counts a tenth of a second at most. The scroll is applied without the scroll animation. The Libraries panel's list uses the same function. Test: `panels::layers` test `a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate` holds a row for half a second in 15 frames and in 60 frames and compares where the rows come to rest. Docs: docs/target-app-parity.md. --- crates/ui-egui/src/panels.rs | 18 ++++++--- crates/ui-egui/src/panels/layers/tests.rs | 48 ++++++++++++++++++++++- docs/target-app-parity.md | 2 +- 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 340e355f3a..62538d8f2f 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -524,19 +524,27 @@ pub(crate) fn rows_take_delete(ctx: &egui::Context) -> bool { /// How near a scrolled list's top or bottom edge a drag scrolls it ([`scroll_at_edges`]). const DRAG_SCROLL_EDGE: f32 = 28.0; +/// The speed of that scrolling in points per second: at the band's inner side, and added to it at +/// the list's edge. +const DRAG_SCROLL_SPEED: (f32, f32) = (60.0, 280.0); + /// While something is dragged near the top or bottom edge of a scrolled list (`ui`: its contents), /// scroll that way, faster nearer the edge, and draw the next frame so a pointer held still keeps -/// it scrolling. The pointer must be over the list's width. +/// it scrolling. The pointer must be over the list's width. Each frame scrolls by the time it +/// took (a stalled frame counts a tenth of a second at most), so the speed is the same at every +/// frame rate. pub(crate) fn scroll_at_edges(ui: &mut Ui) { let Some(pos) = ui.ctx().pointer_hover_pos() else { return }; let view = ui.clip_rect(); if !view.x_range().contains(pos.x) { return; } - let speed = |depth: f32| if (0.0..DRAG_SCROLL_EDGE).contains(&depth) { 2.0 + 10.0 * (1.0 - depth / DRAG_SCROLL_EDGE) } else { 0.0 }; - let delta = speed(pos.y - view.top()) - speed(view.bottom() - pos.y); - if delta != 0.0 { - ui.scroll_with_delta(vec2(0.0, delta)); + let (slow, more) = DRAG_SCROLL_SPEED; + let speed = |depth: f32| if (0.0..DRAG_SCROLL_EDGE).contains(&depth) { slow + more * (1.0 - depth / DRAG_SCROLL_EDGE) } else { 0.0 }; + let per_second = speed(pos.y - view.top()) - speed(view.bottom() - pos.y); + if per_second != 0.0 { + let dt = ui.input(|i| i.stable_dt).min(0.1); + ui.scroll_with_delta_animation(vec2(0.0, per_second * dt), egui::style::ScrollAnimation::none()); ui.ctx().request_repaint(); } } diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 90091dceeb..2b2b609ae2 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1235,10 +1235,21 @@ fn dragging_rows_moves_them_into_other_layers_and_alt_copies() { /// One headless frame of the panel on a short screen (300 × 260) with `events` (Alt held when /// `alt`): for every row name painted inside the list's view, its center, and the view. fn short_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, alt: bool) -> (HashMap, egui::Rect) { + timed_short_frame(app, ctx, events, alt, 1.0 / 60.0) +} + +/// [`short_frame`] for a frame that comes `dt` seconds after the one before it. +fn timed_short_frame( + app: &mut VectorcraftApp, + ctx: &egui::Context, + events: Vec, + alt: bool, + dt: f32, +) -> (HashMap, egui::Rect) { let mut events = events; events.insert(0, egui::Event::ModifiersChanged(egui::Modifiers { alt, ..Default::default() })); let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 260.0)); - let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), predicted_dt: dt, ..Default::default() }, |ui| show(app, ui)); out.textures_delta.clear(); // The rows' eye column dividers are drawn clipped to the list's view. let border = Tokens::get(ctx).input_border; @@ -1342,6 +1353,41 @@ fn rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view() assert_eq!(names[2], "Layer 2", "the original stays"); } +#[test] +fn a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate() { + // Layer 30 held just above the list's bottom edge for half a second, drawn in `frames` frames, + // then moved beside the list, where the scrolling stops: → where the rows in view came to rest. + let held = |frames: u16| { + let mut app = thirty_layers(); + let ctx = egui::Context::default(); + let (names, view) = short_frame(&mut app, &ctx, vec![], false); + let grab = names["Layer 30"]; + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)], false); + short_frame(&mut app, &ctx, vec![button(grab, true)], false); + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab + vec2(0.0, 6.0))], false); + let dt = 0.5 / f32::from(frames); + timed_short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(egui::pos2(grab.x, view.bottom() - 3.0))], false, dt); + for _ in 1..frames { + timed_short_frame(&mut app, &ctx, vec![], false, dt); + } + short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(egui::pos2(view.right() + 2.0, view.bottom() - 3.0))], false); + let mut rows = HashMap::new(); + for _ in 0..120 { + rows = short_frame(&mut app, &ctx, vec![], false).0; + } + // (Layer 30's dimmed copy follows the pointer.) + rows.remove("Layer 30"); + rows + }; + let (at_30, at_120) = (held(15), held(60)); + assert!(!at_30.contains_key("Layer 29") && !at_30.is_empty(), "the list scrolled: {at_30:?}"); + assert_eq!(at_30.len(), at_120.len(), "{at_30:?} {at_120:?}"); + for (name, a) in &at_30 { + let b = at_120.get(name).unwrap_or_else(|| panic!("{name} is in view at 30 frames a second only: {at_120:?}")); + assert!((a.y - b.y).abs() < 2.0, "{name}: {a:?} at 30 frames a second, {b:?} at 120"); + } +} + #[test] fn the_list_scrolls_only_for_rows_held_over_it() { let mut app = thirty_layers(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 83d10986bc..19ad4320b4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -832,7 +832,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). - In the Layers panel only the primary mouse button drags. A drag with the right or middle button on a row, a guide row, the selection square, the eye or lock column or a target circle moves, copies, hides, locks and transfers nothing and records no undo step, and a right-click still opens the row's menu (`panels::layers` test `only_the_primary_button_drags_rows_guides_art_columns_and_appearances`). - - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge, and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view` and `the_list_scrolls_only_for_rows_held_over_it`). + - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge (60 points a second at the band's inner side, 340 at the edge, at every frame rate), and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view`, `a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate` and `the_list_scrolls_only_for_rows_held_over_it`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. - A floating panel's OS window hides while a tool group's flyout or the All Tools drawer is open in the main window, as it does under a modal dialog or a menu, and shows again when the flyout or the drawer closes (#5813; `a_tool_flyout_hides_the_palette_windows_until_it_closes`). - On the desktop a floating panel in an OS window stores the monitor it is on and reopens there at the next launch. When that monitor is no longer connected, the panel opens on the main window's monitor at the same offset (#5582). Outside macOS, a desktop whose monitors have different scale factors keeps opening floating panels on the main window's monitor. Test: `panel_docking::native_tests::a_floating_panel_reopens_on_the_monitor_where_it_was_left`. From 6b799457844e4e12b1f6cbbd2c4822fe627e6859 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:33:55 -0800 Subject: [PATCH 15/28] Toolbars: deleting or renaming a toolbar ends the drag of its title bar Escape during a drag puts the toolbar back by its name. A toolbar deleted while its title bar was dragged left the drag in place, so Escape docked and moved another toolbar that had taken the name since. Deleting the toolbar, or renaming it to a name that differs by more than case, now ends the drag. The drag of another toolbar goes on. The drag test also presses Escape in the frame of the first move after the press, where no drag starts. --- crates/ui-egui/src/custom_toolbars.rs | 57 ++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 2b4618048a..31f83c8bba 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -241,7 +241,8 @@ fn index(ui: &UiState, name: &str) -> Result { /// The All Tools drawer beside the toolbar named `old`, and a group's flyout open on it (`ctx`), /// close when it is deleted (`new` is `None`) or renamed; a new name that changes only the case -/// leaves them open on it. +/// leaves them open on it. A drag of its title bar in progress ends with them, so Escape does not +/// put a toolbar that takes the name later back where this one was. fn close_popups(ui: &mut UiState, ctx: Option<&egui::Context>, old: &str, new: Option<&str>) { let same = new.is_some_and(|n| key(n) == key(old)); if drawer_target(ui).map(key) == Some(key(old)) { @@ -253,6 +254,9 @@ fn close_popups(ui: &mut UiState, ctx: Option<&egui::Context>, old: &str, new: O } } let Some(ctx) = ctx else { return }; + if !same && ctx.data(|d| d.get_temp::(move_id())).is_some_and(|m| key(&m.name) == key(old)) { + ctx.data_mut(|d| d.remove::(move_id())); + } let id = crate::toolbar::flyout_toolbar_id(); if ui.flyout.is_some() && ctx.data(|d| d.get_temp::>(id)).flatten().is_some_and(|t| key(&t) == key(old)) { if same { @@ -2099,6 +2103,52 @@ mod tests { assert_eq!(app.ui.flyout, None, "deleted, then its name taken"); } + /// Deleting or renaming a toolbar while its title bar is dragged ends the drag: Escape then + /// leaves a toolbar that took its name where it is. The drag of another toolbar goes on, and so + /// does the drag of a toolbar whose new name changes only the case. + #[test] + fn deleting_or_renaming_the_toolbar_being_dragged_ends_its_drag() { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + // A drag of the toolbar's title bar in progress, begun where the toolbar is now. + let hold = |app: &VectorcraftApp, name: &str| { + let bar = find(&app.ui, name).unwrap(); + let m = Move { + name: bar.name.clone(), + from: pos2(10.0, 10.0), + grab: egui::Vec2::ZERO, + dock: bar.dock, + right: bar.dock_right, + pos: bar.pos, + cancelled: false, + }; + ctx.data_mut(|d| d.insert_temp(move_id(), m)); + }; + let held = || ctx.data(|d| d.get_temp::(move_id())).is_some(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("window.toolbar.new", json!({"name": "Other"})).unwrap(); + app.run("window.toolbar.dock", json!({"name": "Mine", "side": "right"})).unwrap(); + hold(&app, "Mine"); + delete(&mut app.ui, Some(&ctx), "Other").unwrap(); + assert!(held(), "another toolbar's delete leaves the drag going"); + delete(&mut app.ui, Some(&ctx), "Mine").unwrap(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let at = find(&app.ui, "Mine").unwrap().pos; + assert!(!cancel(&mut app.ui, &ctx), "the deleted toolbar's drag ended"); + assert_eq!((place(&app, "Mine"), find(&app.ui, "Mine").unwrap().pos), ((None, false), at), "deleted, then its name taken"); + app.run("window.toolbar.dock", json!({"name": "Mine", "side": "right"})).unwrap(); + hold(&app, "Mine"); + rename(&mut app.ui, Some(&ctx), "Mine", "mine").unwrap(); + assert!(held(), "a new name that changes only the case leaves the drag going"); + rename(&mut app.ui, Some(&ctx), "mine", "Pens").unwrap(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let at = find(&app.ui, "Mine").unwrap().pos; + assert!(!cancel(&mut app.ui, &ctx), "the renamed toolbar's drag ended"); + assert_eq!((place(&app, "Mine"), find(&app.ui, "Mine").unwrap().pos), ((None, false), at), "renamed, then its name taken"); + assert_eq!(place(&app, "Pens"), (Some(0), true), "the renamed toolbar stays docked"); + } + /// A toolbar deleted while Manage Toolbars has it selected leaves none selected, and a click /// on + or the trash can meant for it does nothing, so the dialog can go on. #[test] @@ -2677,6 +2727,9 @@ mod tests { // Escape while it is dragged out of the lane puts it back in its place. drag(&mut app, grip(&ctx), pos2(600.0, 300.0), Some(4)); assert_eq!(place(&app, "Mine"), (Some(0), false), "Escape keeps it docked"); + // Escape in the frame of the first move after the press: no drag starts. + drag(&mut app, grip(&ctx), pos2(600.0, 300.0), Some(1)); + assert_eq!(place(&app, "Mine"), (Some(0), false), "Escape with the first move keeps it docked"); // Dragged out of the lane, it floats under the pointer. drag(&mut app, grip(&ctx), pos2(600.0, 300.0), None); assert_eq!(place(&app, "Mine"), (None, false)); @@ -2685,6 +2738,8 @@ mod tests { let at = find(&app.ui, "Mine").unwrap().pos; drag(&mut app, grip(&ctx), pos2(1195.0, 400.0), Some(5)); assert_eq!((place(&app, "Mine"), find(&app.ui, "Mine").unwrap().pos), ((None, false), at)); + drag(&mut app, grip(&ctx), pos2(1195.0, 400.0), Some(1)); + assert_eq!((place(&app, "Mine"), find(&app.ui, "Mine").unwrap().pos), ((None, false), at), "Escape with the first move"); // Dropped on the right edge, it docks there. drag(&mut app, grip(&ctx), pos2(1195.0, 400.0), None); assert_eq!(place(&app, "Mine"), (Some(0), true)); From dd676a4243e48671bd422b85f5d37f6d114bb287 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:34:57 -0800 Subject: [PATCH 16/28] Font menu: the app keeps responding when a sample finishes while a font field is drawn A font family field looked up its wheel state with `ui.data(|d| ... ui.ctx().viewport_id() ...)`, in two places. The closure of `ui.data` runs with the egui context read-locked, and `viewport_id()` locks it for reading again. The threads that render the menu's samples call `request_repaint()` when they finish, which locks the context for writing. A write request that arrives between the two reads waits for the first read to end, and the second read waits behind the write request, so neither thread goes on. A release build stays blocked; a debug build of egui panics after ten seconds with "Failed to acquire RwLock read after 10s". `font_menu` now reads the viewport id once, before either `ui.data` call, and uses the resulting id in both. The new test draws a closed font field for 2,000 passes while four threads call `request_repaint()` on the same context. With either lookup put back inside its closure, it fails with that panic. --- crates/ui-egui/src/font_menu.rs | 12 ++++--- crates/ui-egui/src/tests/font_menu.rs | 48 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 4fbb7a7ffc..577f23a8ce 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -367,7 +367,11 @@ pub fn font_menu( let state_id = ui.scope_id().with(&id).with("font-menu"); let mut st: MenuState = ui.data(|d| d.get_temp(state_id)).unwrap_or_default(); ui.data(|d| d.get_temp::(filters_id())).unwrap_or_default().apply(&mut st); - let target = ui.data(|d| d.get_temp(wheel_fields_id(ui.ctx().viewport_id()).with("target"))); + // The viewport is read outside `ui.data`. The closure of `ui.data` runs with the context + // locked, and a second lock taken inside it blocks once a font-sample thread is waiting to + // request a repaint. + let wheel_fields = wheel_fields_id(ui.ctx().viewport_id()); + let target = ui.data(|d| d.get_temp(wheel_fields.with("target"))); let target_changed = st.wheel_target != target; if target_changed { st.wheel_order = None; @@ -435,10 +439,8 @@ pub fn font_menu( out = Some(FontPick::Wheel(steps)); } } - let queued = ui.data(|d| { - d.get_temp::(wheel_fields_id(ui.ctx().viewport_id())) - .is_some_and(|fields| fields.queued.iter().any(|event| event.field == field.id)) - }); + let queued = + ui.data(|d| d.get_temp::(wheel_fields).is_some_and(|fields| fields.queued.iter().any(|event| event.field == field.id))); if drawn || (!field.contains_pointer() && !queued) { st.wheel_order = None; ui.data_mut(|d| d.remove::(field.id.with("wheel"))); diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 47d6258a1d..7ab5378e14 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -1058,6 +1058,54 @@ fn open_menu_with(id: &str, left: f32, width: f32, screen: egui::Vec2, look: Men drawn } +/// The field is drawn while other threads ask the context for repaints, as the threads that +/// render the samples do when they finish. A read of the context made while the menu already +/// holds one waits behind such a request, and a debug build of egui panics after ten seconds. +#[test] +fn the_field_draws_while_other_threads_request_repaints() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + + /// Stops the threads when the test ends, failed or not. + struct Stop(Arc); + impl Drop for Stop { + fn drop(&mut self) { + self.0.store(true, Ordering::Relaxed); + } + } + + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let stop = Stop(Arc::default()); + let (started, running) = std::sync::mpsc::channel(); + let threads: Vec<_> = (0..4) + .map(|_| { + let (ctx, stop, started) = (ctx.clone(), stop.0.clone(), started.clone()); + std::thread::spawn(move || { + let _ = started.send(()); + while !stop.load(Ordering::Relaxed) { + ctx.request_repaint(); + } + }) + }) + .collect(); + for _ in &threads { + running.recv().expect("the thread started"); + } + // The wheel on: the field also looks up its queued wheel input. + let look = MenuLook { wheel: true, ..Default::default() }; + for _ in 0..2000 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + font_menu(ui, "test-repaints", "Inter", 200.0, None, look); + }); + out.textures_delta.clear(); + } + drop(stop); + for thread in threads { + thread.join().expect("the thread ended"); + } +} + /// A narrow field, such as the Control bar's, opens a menu wide enough for the filters on their /// rows and for the families' names, each drawn whole beside its sample. #[test] From d211e2f61302074991d2022add6dd6e587ba6b25 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:35:28 -0800 Subject: [PATCH 17/28] Artboards: a batch's Fit to Artwork Bounds step fits every selected artboard A Fit to Artwork Bounds step of `command.batch` that names neither `index` nor `indices` now fits the artboards the Artboard tool has selected when the step runs (two or more), as the command does when the app runs it on its own. Before, the step took the batch's `artboard` as its `index`, so an action played from the Actions panel fitted only the active artboard while several were selected. - A step's own `index` or `indices` is kept, and the batch no longer adds an unused `index` to a step that names `indices`. - The batch's journal entry records the `indices` the step took, so a replay fits the same artboards. An action leaves them out and fits the artboards selected when it plays. Docs: command.batch params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/batch.rs | 25 +++++- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/command_sets.rs | 4 +- crates/engine/src/tests/journal.rs | 81 ++++++++++++++++++++ crates/ui-egui/src/panels/artboards/tests.rs | 22 ++++++ docs/mcp.md | 8 +- docs/target-app-parity.md | 3 +- 7 files changed, 136 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 18bc78b5d9..8ca723b370 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -78,8 +78,11 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { /// `artboard`, as the Artboards panel shows it in the document the step runs in: past that /// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names /// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with -/// several artboards selected, pastes on those. A step that resizes the active artboard -/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`. +/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither +/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the +/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that +/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor +/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`. /// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them. fn run_steps( s: &mut Session, @@ -110,9 +113,22 @@ fn run_steps( // Artboard tool is chosen with several artboards selected, pastes on those. let names_artboards = id.starts_with("edit.pasteIn") && (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty())); + // A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard + // tool is chosen with several artboards selected, fits those, as the command does on its own. + let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() { + crate::cmd::edit::artboard_tool_picks(s) + } else { + Vec::new() + }; + if !fit_picks.is_empty() + && let Some(o) = params.as_object_mut() + { + o.insert("indices".into(), json!(fit_picks)); + } if let Some(a) = artboard && let Some(key) = key && params.get(key).is_none() + && !(id == "artboard.fitToArt" && params.get("indices").is_some()) && !names_artboards && let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1)) && let Some(o) = params.as_object_mut() @@ -129,8 +145,9 @@ fn run_steps( } grouped.push(step_groups(s, start, &held)); // The step's journal entry records what it took from the preferences or the clock (a - // save's date, a new document's), as a command of its own would. - if noted != params + // save's date, a new document's), as a command of its own would, and the artboards a Fit to + // Artwork Bounds step took from the Artboard tool. + if (noted != params || !fit_picks.is_empty()) && let Some(c) = c.as_object_mut() { c.insert("params".into(), noted); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 26272d873d..ed6ff95808 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index a17fbaf3f8..89642a6e19 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -19,7 +19,9 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ /// The commands that resize the artboards the app passes (Object › Artboards): the app passes the /// selected artboards to Fit to Artwork Bounds as its `indices`, and the active artboard to Fit to /// Selected Art as its `index`. A `command.batch` given `artboard` passes it on, as `index`, to -/// each of their steps that names none. +/// each of their steps that names none; a Fit to Artwork Bounds step that names neither `index` nor +/// `indices`, while the Artboard tool is chosen with several artboards selected, gets those as its +/// `indices` instead. pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"]; /// `(command, param)` pairs the journal records only so a replay reproduces the original run diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index f6ee8015be..5eb66ec6c8 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -192,6 +192,87 @@ fn fit_steps_take_the_batchs_artboard_and_actions_leave_out_their_index() { assert_eq!(action, [fit("artboard.fitToArt"), fit("artboard.fitToArt"), fit("artboard.fitToSelection")]); } +/// A document of three artboards with art of its own on each → its artboards before any fit. +fn three_artboards_with_art(s: &mut Session) -> Vec { + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3, "created": null})).unwrap(); + for (x, h) in [(10, 30), (130, 20), (250, 40)] { + s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap(); + } + s.execute("select.all", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect() +} + +/// The artboards of [`three_artboards_with_art`], each fitted to its art. +fn three_fitted_artboards() -> [vectorcraft_geom::Rect; 3] { + let rect = vectorcraft_geom::Rect::new; + [rect(10.0, 10.0, 30.0, 40.0), rect(130.0, 10.0, 150.0, 30.0), rect(250.0, 10.0, 270.0, 50.0)] +} + +/// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard tool +/// is chosen with several artboards selected, fits each of those (not the batch's artboard), as the +/// command does on its own; a step's own `index` or `indices` wins, and with one artboard or none +/// selected the step takes the batch's artboard. +#[test] +fn a_batch_fit_step_uses_the_artboard_tool_selection() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let fit = |params: Value| json!({"artboard": 1, "commands": [{"command": "artboard.fitToArt", "params": params}]}); + let session = |picks: &Value| { + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", picks); + (s, was) + }; + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({}))).unwrap(); + assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "artboards 1 and 3, the selected ones, and not the batch's artboard 2"); + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({"index": 1}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "a step's own index"); + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({"indices": [1, 2]}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], fitted[2]], "a step's own indices"); + for picks in [json!([2]), json!([])] { + let (mut s, was) = session(&picks); + s.execute("command.batch", &fit(json!({}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard with {picks} selected"); + } +} + +/// The journal records the artboards a batch's Fit to Artwork Bounds step took from the Artboard +/// tool, so a replay in a new session fits the same ones; an action leaves them out and fits the +/// artboards selected when it plays. +#[test] +fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + let start = s.journal.len(); + let steps = json!([{"command": "artboard.fitToArt", "params": {}}]); + s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap(); + assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]]); + let (id, p) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({"indices": [0, 2]}))); + let r = replayed(&s); + assert_ne!(r.tool_id(), "artboard", "the new session's tool selects no artboards"); + assert_eq!(boards(&r), boards(&s), "the replay fits the recorded artboards"); + let action = s.journal_for_action(start); + assert_eq!(action, [("command.batch".to_string(), json!({"commands": steps}))]); + // Played on a fresh copy of the document with other artboards selected. + let mut a = Session::new(); + three_artboards_with_art(&mut a); + a.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + a.set_tool_option("selected", &json!([1, 2])); + a.execute("command.batch", &json!({"artboard": 0, "commands": action[0].1["commands"]})).unwrap(); + assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays"); +} + #[test] fn a_save_records_its_date_and_replays_it() { let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned(); diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index eae59fd7dc..b53faf87c0 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -95,6 +95,28 @@ fn fit_to_artwork_bounds_fits_each_selected_artboard_to_its_own_art() { assert_eq!(boards(&app), [rect(10.0, 10.0, 30.0, 40.0), was[1], rect(250.0, 10.0, 270.0, 50.0)]); } +/// A batch the app runs (as the Actions panel plays an action) with a Fit to Artwork Bounds step +/// fits artboards 1 and 3, selected with the Artboard tool, and leaves artboard 2, the active one, +/// as it was. +#[test] +fn a_batchs_fit_to_artwork_bounds_step_fits_each_selected_artboard() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + for (x, h) in [(10, 30), (130, 20), (250, 40)] { + app.session.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap(); + } + app.session.execute("select.all", &json!({})).unwrap(); + app.session.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&app); + app.select_tool("artboard"); + select(&mut app, 1); + app.session.set_tool_option("selected", &json!([0, 2])); + app.run("command.batch", json!({"commands": [{"command": "artboard.fitToArt", "params": {}}]})).unwrap(); + let rect = vectorcraft_geom::Rect::new; + assert_eq!(boards(&app), [rect(10.0, 10.0, 30.0, 40.0), was[1], rect(250.0, 10.0, 270.0, 50.0)]); +} + /// With the Artboard tool, Shift-click on a row selects the artboards from the last row clicked /// without Shift to it and makes it the active one, Ctrl/Cmd-click adds its artboard to the /// tool's selection or takes it out (#1139), a plain click selects it alone, and every selected diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..b07bbb32c8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5373,8 +5373,12 @@ the selected artboards (those the Artboard tool has selected, else the active on `artboard.fitToSelection` calls it runs without `index`. Both include MCP's `run_command` calls in remote mode. The Artboards panel menu's Fit to Artwork Bounds also passes the selected artboards. A batch passes its `artboard` on to each of their steps that names no `index`, as the step's `index`. When the document a step runs in has no artboard at -that index, the step gets that document's last artboard. An action recorded in the Actions panel leaves `index` and -`indices` out of these steps, and they resize the artboard that is active when the action plays. +that index, the step gets that document's last artboard. An `artboard.fitToArt` step that names neither `index` nor +`indices`, while the Artboard tool is chosen with several artboards selected when the step runs, gets those artboards +as its `indices` instead, and the batch's journal entry records them, so a replay of the journal fits the same +artboards. A step's own `index` or `indices` is kept. An action recorded in the Actions panel leaves `index` and +`indices` out of these steps: when the action plays, Fit to Artwork Bounds resizes the artboards the Artboard tool then +has selected (two or more), else the active artboard, and Fit to Selected Art resizes the active artboard. ```json {"name":"run_command","arguments":{"command":"object.align","params":{"horizontal":"left","to":"artboard","artboard":1}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..2cd35afba0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1146,8 +1146,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Align to Artboard chosen, the Align panel's Distribute Objects and Distribute Spacing buttons use the active artboard (`object.distribute` and `object.distributeSpacing` with `to: "artboard"` and `artboard`). The first object's left or top edge goes to the artboard's left or top edge, and the last object's right or bottom edge goes to the artboard's right or bottom edge. Distribute Objects spaces the other objects evenly by its button's line, and two objects are enough. Distribute Spacing makes the gaps between the objects equal. With anchor points selected, the buttons space the points among themselves and do not use the artboard. When an action plays, its Distribute Objects and Distribute Spacing steps with Align to Artboard use the artboard that is active then. With a key object, the Align panel's Distribute Objects buttons use the Distribute Spacing value (`object.distribute {spacing}`): the key object, or the compound path or selected group that contains it, stays in place, and the objects' left edges, centers or right edges (top edges, centers or bottom edges) end up that far apart, outward from the key object's, in their order. With the field's default value of 0, a click puts every object on the key object's line (behavior reference: [Ask Mordy: Distributing Objects](http://rwillustrator.blogspot.com/2008/01/ask-mordy-distribute.html)). Choosing the Artboard tool (Shift+O, its toolbar button, Edit Artboards in Properties or Document Setup, or the Artboards panel menu's Artboard Options…) starts it on the active artboard: the canvas outlines that artboard, and Delete, Cut, Copy, the Transform panel and Artboard Options act on it. - Object › Artboards › Fit to Selected Art resizes the active artboard (`artboard.fitToSelection {index}`). It used to resize artboard 1 whichever artboard was active. When an action plays, its Fit to Artwork Bounds and Fit to Selected Art steps that name no artboard resize the artboard that is active then. + Object › Artboards › Fit to Selected Art resizes the active artboard (`artboard.fitToSelection {index}`). It used to resize artboard 1 whichever artboard was active. When an action plays, its Fit to Selected Art steps that name no artboard resize the artboard that is active then, and its Fit to Artwork Bounds steps resize the artboards selected then. Object › Artboards › Fit to Artwork Bounds and the Artboards panel menu's Fit to Artwork Bounds fit each selected artboard (those the Artboard tool has selected, else the active one) to the art on it, as the public [Use the artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) page describes (`artboard.fitToArt {indices}`). An object partly on an artboard counts for each artboard it overlaps, and an artboard with no art on it keeps its size and place. They used to fit the active artboard to all the art in the document. + A Fit to Artwork Bounds step of a batch run from the app (`command.batch`), including an action played from the Actions panel, fits each artboard the Artboard tool has selected when the step runs, as the command does on its own and as the [help page](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) describes. A step's own `index` or `indices` is kept, and the journal records the artboards the step fitted, so a replay fits the same ones. The step used to fit only the active artboard. The Artboards panel menu's Duplicate Artboards copies each selected artboard (those the Artboard tool has selected, else the active one) with its art, in one undo step, and the copies are then selected, as the public [Use the artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) page describes. With the Artboard tool, Copy and Cut take every selected artboard with its art, as the public [Cut, copy, and paste artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/cut-copy-and-paste-artboards.html) page describes, and Paste brings them all back in one undo step (`artboard.duplicate`, `artboard.copy` and `artboard.cut` with `indices`). The copies keep their places relative to each other, together right of the last artboard. All three used to act on the active artboard only. With the Artboard tool selecting several artboards, Paste in Place, Paste in Front and Paste in Back put a copy of the copied art on each, where it was on the artboard it was copied from, in one undo step, as the public [Cut, copy, and paste artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/cut-copy-and-paste-artboards.html) page describes (`artboards` on the three commands). Art copied from no artboard keeps its place on the first selected artboard and its offset to it on the others, and an `artboard` or `artboards` index the document does not have is an error; these rules are VectorCraft's own. The three commands used to paste one copy, on the active artboard, and an `artboard` index the document did not have pasted the art where it was. A replay of the journal repeats a Cut or Copy made with the Artboard tool on the artboards it took (`edit.cut` and `edit.copy` record `selectedArtboards` and `art`), whichever tool is chosen in the new session and whatever is selected there. A recorded action follows the tool chosen when it plays. The replay used to act on the objects selected then, or stop with nothing selected. This rule is VectorCraft's own. From 9bb22504763234646eae5f11d82155f7808b8004 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:10:35 -0800 Subject: [PATCH 18/28] .ai: an image's Warp effect is saved and opened live An embedded image whose appearance is one Warp effect, with no opacity mask, is written to the editing data with an art style of that Warp: its bent pieces as its drawn look and the image itself on `%_` lines, as other styled objects are written. The reader takes such an image with its Warp live when the live warp draws as the drawn look, using the comparison and budget it uses for warped type; otherwise the drawn look stays, with the drawn-look note. A linked image with a Warp is written as its drawn art, as before, without its live Warp. Images with an opacity mask and images with another effect keep their drawn art. An embedded image whose samples are on `%_` lines is now read as the hidden copy it is. Before, it came in as a second visible object beside its drawn look. --- crates/eps/src/ai_editing/tests.rs | 118 ++++++++++++++++ crates/eps/src/ai_editing/writer/styles.rs | 35 +++-- crates/eps/src/import/ai/read.rs | 6 +- crates/eps/src/import/ai/read/art.rs | 15 +- crates/eps/src/import/ai/read/ops.rs | 151 +++++++++++++++++++-- crates/eps/src/import/ai/style.rs | 8 ++ docs/target-app-parity.md | 1 + 7 files changed, 311 insertions(+), 23 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 8c4e95f4e6..4e779ef98f 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -7109,6 +7109,124 @@ fn every_effect_a_graphic_style_holds_is_read_back() { assert!(p.contains("7.5 /Real (moveV_Pts) ,") && p.contains("0.5236 /Real (rotate_Radians) ,"), "{p}"); } +/// An embedded 8 × 8 image of a color ramp, `Photo`, 80 pt square at (20, 10) in `doc`, at half +/// opacity, with `effects`. +fn warped_photo(doc: &mut Document, effects: Vec) -> Node { + let ramp = image::RgbImage::from_fn(8, 8, |x, y| image::Rgb([(x * 32) as u8, (y * 32) as u8, 160])); + let mut photo = image_node(doc, ImageBlob::png(png_of(ramp.into())), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None); + photo.name = Some("Photo".into()); + photo.opacity = 0.5; + photo.appearance = Appearance { effects, ..Appearance::default() }.into(); + photo +} + +/// A 200 × 100 document holding `photo`, made by [`warped_photo`]. +fn photo_doc(photo: impl FnOnce(&mut Document) -> Node) -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let n = photo(&mut doc); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// An embedded image with one Warp is written with an art style of that Warp, its bent pieces as its +/// drawn look and the image itself on `%_` lines: it reads back as the image, its pixels, placement, +/// name and opacity as they were, with its Warp live and its settings kept. +#[test] +fn an_image_with_a_warp_reads_back_with_its_warp_live() { + // GUARDS: an image with a Warp was written as its drawn pieces alone, and read back without its Warp. + for (id, params) in [ + ("warp.arc", serde_json::json!({"bend": 40.0})), + ("warp.flag", serde_json::json!({"bend": -30.0, "horizontal": 10.0, "vertical": 0.0, "orientation": "vertical"})), + ] { + let doc = photo_doc(|d| warped_photo(d, vec![fx(id, params.clone())])); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{id}: {:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{id}: {:#?} {:?}", lines(&back), out.warnings); + let (mut want, mut got) = (vec![], vec![]); + pictures(&doc, doc.layers[0].children().unwrap(), "", &mut want); + pictures(&back, art, "", &mut got); + assert_eq!(got, want, "{id}"); + let [warp] = art[0].appearance.effects.as_slice() else { panic!("{id}: {:?}", art[0].appearance) }; + assert_eq!(warp.id, id); + let (w, g) = (vectorcraft_effects::merged_params(id, ¶ms), vectorcraft_effects::merged_params(&warp.id, &warp.params)); + for key in ["bend", "horizontal", "vertical"] { + assert!((g[key].as_f64().unwrap() - w[key].as_f64().unwrap()).abs() < 6e-3, "{id} {key}: {g} for {w}"); + } + assert_eq!(g["orientation"], w["orientation"], "{id}"); + } +} + +/// An image whose style's Warp bends it another way than its drawn look keeps that look, with the +/// note, and the file as written opens with the image. +#[test] +fn an_image_whose_warp_draws_otherwise_than_its_look_keeps_its_look() { + // GUARDS: an image read with its Warp live whatever its drawn look showed. + let doc = photo_doc(|d| warped_photo(d, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))])); + let program = export_ai_editing(&doc, &opts()).unwrap().program; + let (from, to) = (b"0.4 /Real (DeformValue)".as_slice(), b"-0.4 /Real (DeformValue)".as_slice()); + let at = program.windows(from.len()).position(|w| w == from).expect("the warp's bend"); + let mut other = program.clone(); + other.splice(at..at + from.len(), to.iter().copied()); + let (back, warnings) = crate::ai_alone(&other).unwrap(); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{art:#?}"); + assert!(matches!(art[0].kind, NodeKind::Group { .. }), "the drawn look: {:?}", art[0].kind); + assert!(art[0].appearance.effects.is_empty(), "{:?}", art[0].appearance); + assert!(warnings.iter().any(|w| w.contains("drawn look")), "{warnings:?}"); + let (back, _) = crate::ai_alone(&program).unwrap(); + assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Image(_))); +} + +/// An image on `%_` lines is the copy of a styled object, as other objects there are: with a style +/// the file doesn't define, its drawn look stands for it, named as it is, and the image doesn't come +/// in beside the look. +#[test] +fn an_image_on_hidden_lines_does_not_come_in_beside_its_look() { + // GUARDS: an image whose samples were on `%_` lines came in as a second, visible object. + let doc = photo_doc(|d| warped_photo(d, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))])); + let program = export_ai_editing(&doc, &opts()).unwrap().program; + let (from, to) = (b"1 (Anon 1) XW".as_slice(), b"1 (Unknown) XW".as_slice()); + let at = program.windows(from.len()).position(|w| w == from).expect("the image's style"); + let mut unknown = program.clone(); + unknown.splice(at..at + from.len(), to.iter().copied()); + let (back, _) = crate::ai_alone(&unknown).unwrap(); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{:#?}", lines(&back)); + assert!(matches!(art[0].kind, NodeKind::Group { .. }), "the drawn look: {:?}", art[0].kind); + assert_eq!(art[0].name.as_deref(), Some("Photo")); +} + +/// A linked image, an image with an opacity mask, and an image with a Warp and another effect are +/// written as their drawn art, with no art style. +#[test] +fn other_warped_images_are_written_as_their_drawn_art() { + let arc = || fx("warp.arc", serde_json::json!({"bend": 40.0})); + let linked = photo_doc(|d| { + let mut n = warped_photo(d, vec![arc()]); + if let NodeKind::Image(im) = &mut n.kind { + im.link = Some(vectorcraft_doc::LinkInfo::new("/art/photo.png")); + } + n + }); + let masked = photo_doc(|d| { + let mut n = warped_photo(d, vec![arc()]); + let white = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 10.0, 100.0, 90.0)), Appearance::basic(solid(Color::WHITE), Paint::None, 0.0)); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(white, false))); + n + }); + let stacked = photo_doc(|d| warped_photo(d, vec![arc(), fx("stylize.feather", serde_json::json!({"radius": 2.0}))])); + for (what, doc) in [("linked", linked), ("masked", masked), ("stacked", stacked)] { + assert!(!program_shown(&doc).contains("1 (Anon"), "{what}"); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert!(art.iter().all(|n| n.appearance.effects.is_empty()), "{what}: {art:#?}"); + } +} + /// Every kind of appearance a style isn't written for is written as its drawn look, with a warning. #[test] fn appearances_written_as_their_drawn_look() { diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 29eb2bf910..fe3e68ce24 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -41,7 +41,8 @@ pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize { /// The objects of `doc`'s layers that may be written with an art style ([`Writer::styled_object`]), /// by id: paths and compound paths with points and groups, with live effects, linked to a graphic -/// style or (paths and compound paths) with a brush on a stroke, without Opacity & Mask Define +/// style or (paths and compound paths) with a brush on a stroke, and embedded images with one Warp +/// ([`warped_image`]), without Opacity & Mask Define /// Knockout Shape (the reader takes an object's transparency /// from its look, which doesn't carry it). A group's members are paths, compound paths or such /// groups, none with effects or anything baking changes. @@ -86,10 +87,22 @@ fn candidate(n: &Node) -> bool { NodeKind::Path { path, guide: false, clipping: false, .. } => has_points(path), NodeKind::Compound { .. } => has_points(&compound_path(n)), NodeKind::Group { children, clip: false } => !n.is_compound_shape() && children.iter().all(|c| plain_member(c)), + NodeKind::Image(_) => warped_image(n), _ => false, } } +/// Is `n` an embedded image without an opacity mask whose appearance is one Warp, with no fills or +/// strokes that paint and no effects on them: an image the reader reads with its Warp live +/// ([`crate::import::read_art_style`]'s `image_warp`)? +fn warped_image(n: &Node) -> bool { + let NodeKind::Image(im) = &n.kind else { return false }; + im.link.is_none() + && n.extras().mask.is_none() + && matches!(n.appearance.effects.as_slice(), [e] if e.id.starts_with("warp.")) + && n.appearance.items.iter().all(|i| i.paint().is_none() && i.effects().is_empty()) +} + /// Does `n` have a stroke with a brush that paints, one that its art style holds ([`Writer::style_text`] /// leaves out what paints nothing)? fn brushed(n: &Node) -> bool { @@ -666,7 +679,7 @@ impl Writer<'_> { return Some(name); } let brushed = brushed(orig); - if (orig.appearance.effects.is_empty() && !brushed) || !own_style_holds(&orig.appearance) { + if (orig.appearance.effects.is_empty() && !brushed) || !(own_style_holds(&orig.appearance) || warped_image(orig)) { return None; } let graded = orig.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_))); @@ -704,7 +717,8 @@ impl Writer<'_> { /// glows or feathers, the object's transparency /// after the group's end, `0 0 Xd`, `6 () XW`); the object itself on `%_` lines (a path's or /// compound path's points painted with nothing, or with its gradient fill when its style has - /// one; a group with its members), its name and opacity mask; then `1 (name) XW`. + /// one; a group with its members; an image with its pixels), its name and opacity mask; then + /// `1 (name) XW`. /// The look's group and the object itself are counted first ([`Self::take_objects`]): without /// room for them, nothing is written, and the object counts neither as written with its graphic /// style nor as written with a brush on its stroke. @@ -712,7 +726,7 @@ impl Writer<'_> { let own = match &orig.kind { NodeKind::Path { path, .. } => super::object_count(path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()), NodeKind::Compound { .. } => super::object_count(compound_path(orig).subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()), - NodeKind::Group { .. } => 1, + NodeKind::Group { .. } | NodeKind::Image(_) => 1, _ => 0, }; if !self.take_objects(1 + own) { @@ -752,13 +766,14 @@ impl Writer<'_> { let saved = std::mem::take(&mut self.body); self.hidden += 1; let fit = drawn_outline(n, orig).map(|p| p.bounding_box()); - // A path's objects were kept for it above; it counts them itself. + // A path's or an image's objects were kept for it above; it counts them itself. if !matches!(orig.kind, NodeKind::Group { .. }) { self.objects -= own; } match &orig.kind { NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy), NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy), + NodeKind::Image(im) => self.image(&self.doc.shown_image(orig, im), xy), NodeKind::Group { children, .. } => { self.line("u"); for c in children { @@ -847,7 +862,8 @@ fn object_rule(n: &Node) -> FillRule { /// Can appearance `ap` be written as a style of an object's own: fills and strokes that paint without /// transparency or effects of their own, and no Warp, Distort & Transform or Blur effect? Those -/// are written only in the Graphic Styles panel's styles. +/// are written only in the Graphic Styles panel's styles, apart from a Warp on an image +/// ([`warped_image`]). fn own_style_holds(ap: &Appearance) -> bool { let plain = |i: &AppearanceItem| i.opacity() >= 1.0 && i.blend() == BlendMode::Normal && i.effects().is_empty(); let panel_only = |e: &Effect| ["warp.", "distort.", "blur."].iter().any(|p| e.id.starts_with(p)); @@ -870,13 +886,16 @@ fn panel_reads(g: &GraphicStyle, text: &str) -> bool { /// Does the reader read object `n` written with style text `text` as it is: a path or compound /// path with a style it reads on any object, filled by the non-zero rule when the style fills it, /// or a group with no fills or strokes of its own, with effects that move the outline only where the -/// reader reads them ([`crate::import::style_moves_with`])? +/// reader reads them ([`crate::import::style_moves_with`]), or an image ([`warped_image`]) with a +/// style of one Warp? The reader takes such an image's Warp where it draws as its drawn look. fn object_reads(n: &Node, text: &str) -> bool { let section = known_style("x", text); let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_))); let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false }; let group = matches!(n.kind, NodeKind::Group { .. }); - if !read.simple + let image = matches!(n.kind, NodeKind::Image(_)); + if (image && !(read.image_warp && warped_image(n))) + || (!image && !read.simple) || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) || !crate::import::style_moves_with(section.as_bytes(), "x", n) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 3721ce7960..4b2936f56e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -483,6 +483,9 @@ struct Reader<'a> { /// a global process colour, so these make swatches only for names no colour operator defines. stop_spots: Vec, raster: Option, + /// The samples of the image being read are on `%_` lines (`%_%%BeginData`): it is the copy of + /// a styled object there, as the other objects on those lines are. + image_hidden: bool, /// The file `XG` names for the image after it (`XF`), until an image is read. image_link: Option, /// The placed file being read (`%AI5_BeginPlace` … `~`). @@ -736,6 +739,7 @@ impl<'a> Reader<'a> { spots: Vec::new(), stop_spots: Vec::new(), raster: None, + image_hidden: false, image_link: None, place: None, foreign_data: None, @@ -846,7 +850,7 @@ impl<'a> Reader<'a> { self.op(w, hidden)?; } Tok::Comment(c) => self.comment(c, hidden)?, - Tok::Data(d) => self.image(d)?, + Tok::Data(d) => self.image(d, hidden)?, Tok::Preview(d) => { if let Some(p) = self.place.as_mut() { p.preview = preview_png(d); diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3d859bf74e..7e0f91e993 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -370,15 +370,18 @@ impl<'a> Reader<'a> { // ---- images ---------------------------------------------------------------------------- - /// The samples after `XI`, its operands on the stack. - pub(super) fn image(&mut self, data: &[u8]) -> Result<(), String> { + /// The samples after `XI`, its operands on the stack; `hidden` when they are on `%_` lines. + pub(super) fn image(&mut self, data: &[u8], hidden: bool) -> Result<(), String> { let vals = self.operands(); // Operands that came before an `XI` on their own line. let vals = match self.raster.as_mut().and_then(|r| r.operands.take()) { Some(before) if !vals.iter().any(|v| matches!(v, V::Arr(_))) => before, _ => vals, }; - self.image_from(vals, data, false) + self.image_hidden = hidden; + let read = self.image_from(vals, data, false); + self.image_hidden = false; + read } /// The matrix and the numbers of an image's operands (`[a b c d tx ty] llx lly urx ury w h bits @@ -713,7 +716,8 @@ impl<'a> Reader<'a> { /// Add the image `blob` (`w` × `h` pixels), which the matrix `m` maps into art space, with /// `alpha` (its alpha channel, one byte a pixel) as its opacity mask when it hides part of the - /// image, and `colorize` as the color that colorizes it. + /// image, and `colorize` as the color that colorizes it. It is on `%_` lines when its samples + /// are ([`Self::image`]). fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32), colorize: Option) -> Result<(), String> { // The matrix is an art-space matrix (y up) applied to the pixels with their rows running // downwards, (u, -v): pixels → (u, -v) → art space. Flipping the matrix's result instead @@ -735,7 +739,8 @@ impl<'a> Reader<'a> { let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }; - self.add_image_colorized(im, mask, colorize, false) + // An image on `%_` lines is the copy of a styled object, as the other objects there are. + self.add_image_colorized(im, mask, colorize, self.image_hidden) } /// An image that isn't read is left out, with `warning`; in a symbol's art, the symbol isn't diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 9f6a1dd6af..f79e7b9108 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -748,6 +748,7 @@ impl<'a> Reader<'a> { } let space = self.space(); self.note_brushes_kept(); + let page = self.page_in_doc(); let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else { @@ -780,7 +781,7 @@ impl<'a> Reader<'a> { look }; // A style read here: the object, painted as it says. - if let Some(mut appearance) = self.styles.get(&style).and_then(|st| { + let appearance = self.styles.get(&style).and_then(|st| { styled( object, look, @@ -796,13 +797,32 @@ impl<'a> Reader<'a> { space, }, ) - }) { - // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). - let k = space.determinant().abs().sqrt(); - if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { - appearance.scale_strokes(k); - appearance.scale_effects(k, vectorcraft_effects::scale_effect); + .map(|mut appearance| { + // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). + let k = space.determinant().abs().sqrt(); + if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { + appearance.scale_strokes(k); + appearance.scale_effects(k, vectorcraft_effects::scale_effect); + } + appearance + }) + }); + // An image with a Warp is the object only where its live warp draws as its drawn look, and + // while the import has a check left for it; otherwise its drawn look stays. + let appearance = match appearance { + Some(ap) if matches!(object.kind, NodeKind::Image(_)) && ap.effects.iter().any(|e| e.id.starts_with("warp.")) => { + let alike = self.envelope_checks > 0 && { + self.envelope_checks -= 1; + let layer = self.doc.alloc_id(); + let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; + let shown = !hidden && object.visible && look.visible; + image_warp_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + }; + alike.then_some(ap) } + other => other, + }; + if let Some(appearance) = appearance { let Some(mut object) = f.children.pop() else { return }; let Some(look) = f.children.pop() else { return }; let left_out = look.visual_bounds().filter(|_| !hidden && object.visible && look.visible); @@ -1116,6 +1136,41 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { }) } +/// Is `object` an image without an opacity mask, and `st` one Warp on it with nothing else that +/// paints ([`crate::import::ai::style::ArtStyle::image_warp`])? Such an image is read with its Warp +/// live where that draws as its drawn look ([`image_warp_alike`]). +fn image_warps(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { + matches!(object.kind, NodeKind::Image(_)) && object.extras().mask.is_none() && st.image_warp +} + +/// Does image `object` with `appearance` (its style's Warp) draw as `look`, its drawn look, compared +/// over all that the warp draws ([`crate::import::ai::envelope::warped_alike`]) on `layer`, a layer +/// id no other node has? Both are drawn shown, opaque and in the Normal mode. Unless the look is on +/// `%_` lines itself (`hidden`), the copies in it that are on `%_` lines (`hidden_ids`) are left out. +#[allow(clippy::too_many_arguments)] +fn image_warp_alike( + object: &Node, + appearance: &Appearance, + look: &Node, + hidden_ids: &HashSet, + hidden: bool, + layer: NodeId, + shared: &crate::import::ai::envelope::Shared<'_>, + page: Option, + spent: &mut crate::import::ai::envelope::Spent, +) -> bool { + let mut live = object.clone(); + live.appearance = appearance.clone().into(); + let mut plain = look.clone(); + if !hidden { + strip(&mut plain, hidden_ids); + } + for n in [&mut live, &mut plain] { + (n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal); + } + crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent) +} + /// What [`placed_paints`] keys a pattern's name with, apart from the gradients' names. const PATTERN_KEY: &str = "\u{1}pattern "; @@ -1128,11 +1183,13 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let slot = slot_of(object.name.as_deref()).is_some(); // Several fills and strokes, on a path or a compound path. let stacked = !slot && !st.simple && st.stacked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + // One Warp on an image, checked against its drawn look by the caller ([`image_warp_alike`]). + let image_warp = !st.simple && image_warps(object, st); // A symbol instance draws its symbol's art: it keeps its drawn look. if !st.plain || matches!(object.kind, NodeKind::SymbolInstance { .. }) // A look with no outline in it to keep takes a variable-width stroke as the object's own. - || (!slot && !st.simple && !stacked && (!st.uneven || draws(look, &HashSet::new()))) + || (!slot && !st.simple && !stacked && !image_warp && (!st.uneven || draws(look, &HashSet::new()))) || (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty()) || (st.pathfinder && (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. }))) @@ -1266,6 +1323,9 @@ pub(crate) struct StyleRead { pub appearance: Appearance, /// An object other than type is read with it ([`crate::import::ai::style::ArtStyle::simple`]). pub simple: bool, + /// An image without an opacity mask is read with it where its live warp draws as its drawn + /// look ([`crate::import::ai::style::ArtStyle::image_warp`]). + pub image_warp: bool, /// It has Effect › Pathfinder effects, which only a group with no fills or strokes is read with. pub pathfinder: bool, /// The opacity, blending mode, isolation and knockout its blend filter gives. @@ -1310,7 +1370,7 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P s.brush = Some(brush); } } - Some(StyleRead { appearance, simple: st.simple, pathfinder: st.pathfinder, transparency: st.transparency }) + Some(StyleRead { appearance, simple: st.simple, image_warp: st.image_warp, pathfinder: st.pathfinder, transparency: st.transparency }) } /// Is art style `name` of `section` read on `object` as far as an effect that moves the outline @@ -1519,6 +1579,79 @@ mod tests { assert!(styled(&Node::new(NodeId(4), NodeKind::Image(Box::new(image))), &look, st, &paints).is_none()); } + /// The style `Fx`: `effects` (each a filter's name and its dictionary's keys) on the whole + /// object, over a fill and a stroke that `paints` turns on (`0 1`: the fill paints blue). + fn effects_style(effects: &[(&str, &str)], paints: &str) -> crate::import::ai::style::ArtStyle { + let filters: String = effects + .iter() + .map(|(name, keys)| { + format!("/BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n") + }) + .collect(); + let text = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + {filters}/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n{paints} Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ); + crate::import::ai::style::art_styles(text.as_bytes()).remove("Fx").unwrap_or_default() + } + + /// An image takes a style of one Warp, under fills and strokes that paint nothing, and no + /// other style with a geometry effect: those keep its drawn look. A path, and an image with an + /// opacity mask, keep their drawn look with the Warp too. + #[test] + fn an_image_takes_a_style_of_one_warp_alone() { + // GUARDS: an image with a Warp in its art style came in as its drawn look. + let warp = ("Adobe Deform", "1 /Int (DeformStyle) ,\n0.4 /Real (DeformValue) ,\n"); // brand-ok: the filter's name in the files + let (gradients, patterns, names, v7_patterns, bending) = + (HashMap::new(), HashMap::new(), ShownNames::default(), HashSet::new(), HashSet::new()); + let paints = StylePaints { + gradients: &gradients, + patterns: &patterns, + names: &names, + v7_patterns: &v7_patterns, + brushes: &[], + kept: &[], + bending: &bending, + space: Affine::IDENTITY, + }; + let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(NodeId(4), NodeKind::Image(Box::new(image))); + let st = effects_style(&[warp], "0 0"); + assert!(st.image_warp && !st.simple, "{st:?}"); + let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp"); + let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["warp.arc"]); + assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}"); + // Not on a path, nor on an image with an opacity mask. + assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none()); + let mut masked = image.clone(); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(styled(&masked, &look, &st, &paints).is_none()); + // A Warp over a fill that paints, a Warp with another effect, and the other geometry effects. + let still = ("Adobe Punk and Bloat", "0 /Real (d_factor) ,\n"); + let others: [(&[(&str, &str)], &str); 8] = [ + (&[warp], "0 1"), + (&[warp, still], "0 0"), + (&[still, warp], "0 0"), + (&[("Adobe Twirl", "45 /Real (angle) ,\n")], "0 0"), + (&[("Adobe Free Distort", "")], "0 0"), + (&[("Adobe Punk and Bloat", "-50 /Real (d_factor) ,\n")], "0 0"), + (&[("Adobe Zigzag", "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n")], "0 0"), + (&[("Adobe Transform", "5 /Real (moveH_Pts) ,\n0.5 /Real (rotate_Radians) ,\n0 /Bool (transformPatterns) ,\n")], "0 0"), + ]; + for (effects, painted) in others { + let st = effects_style(effects, painted); + assert!(!st.image_warp, "{effects:?} {painted}"); + assert!(styled(&image, &look, &st, &paints).is_none(), "{effects:?} {painted}"); + } + } + #[test] fn data_stops_at_its_end_or_a_marker_of_the_section() { let section = Some(("BeginTextDocument", "EndTextDocument")); diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 482c172386..d27a297925 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -193,6 +193,10 @@ pub(super) struct ArtStyle { /// the effects any object takes that don't move the outline: what a path or compound path is /// read with when each gradient is placed as its drawn look has it (`read::ops`' `styled`). pub stacked: bool, + /// It is one Warp on the whole object, under fills and strokes that paint nothing and have no + /// effects of their own: what an image is read with when its live warp draws as its drawn look + /// (`read::ops`' `styled`). + pub image_warp: bool, /// Its fills and strokes, bottom first. pub items: Vec, /// Each item's own visibility, transparency and effects, in the order of [`Self::items`]. @@ -1778,6 +1782,10 @@ fn style(filters: &[Filter]) -> ArtStyle { && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Stroke { brush: None, .. })) && st.looks.iter().all(|l| l.effects.is_empty()) && st.effects.iter().all(any_object_takes); + st.image_warp = st.plain + && matches!(st.effects.as_slice(), [e] if e.id.starts_with("warp.")) + && st.items.iter().all(|i| matches!(i, StyleItem::Fill(p) | StyleItem::Stroke { paint: p, .. } if p.is_none())) + && st.looks.iter().all(|l| l.effects.is_empty()); st } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..d845b91f87 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -610,6 +610,7 @@ since 2026-10-01. - **Placed gradients follow the Warp effects:** under each of the fifteen Warp styles with a bend or a distortion, a gradient placed with the Gradient tool moves and scales from the object's bounds before the warp to its bounds after it, as under Free Distort; a stroke's gradient uses those bounds inflated by the stroke. This holds for an object's own Warp and for a fill's or stroke's own, on the canvas and in Object › Expand of the fill. In a group with a Warp effect, each path's and compound path's gradients follow its own bounds, a nested group's own fills and strokes follow the nested group's bounds, and the group's own fills and strokes follow the group's bounds. In the art Pathfinder and compound shapes take, a symbol instance's Warp moves the gradients of its symbol's art by the art's bounds, and a compound shape's Warp moves its gradients by the bounds of its area. A gradient fitted to the object still fits the warped outline, and a warp with no bend and no distortion leaves the gradient exactly in place. Existing documents with a Warp effect on art with a placed gradient draw differently: before, the gradient stayed where it was while the outline changed. How gradients follow the warp is VectorCraft's own rule; what the Warp effects do to the object is described in [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) (effects `tests::warp_bends_when_the_warp_moves_the_outline`, `bake::tests::baked_warps_move_placed_gradients_from_the_bounds_to_the_warped_bounds`, `bake::tests::a_warp_with_no_bend_leaves_a_placed_gradient_exactly_in_place`, `bake::tests::a_fills_and_a_strokes_own_warp_move_its_placed_gradient_with_the_bounds`, `group::tests::a_groups_warp_moves_the_gradients_placed_on_its_paths_by_each_paths_bounds`, `group::tests::a_groups_warp_moves_its_own_a_nested_groups_and_a_compound_paths_gradients_by_their_bounds`, `group::tests::shape_art_moves_the_gradients_of_a_symbol_instances_art_and_a_compound_shape_with_a_warp`; render `objectfx::a_paths_gradient_moves_and_scales_with_its_warped_bounds`; engine `objexpand::a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Warp as a Bézier patch per style:** each of the fifteen Warp styles bends the object's bounds as one Bézier patch whose control points the style sets from the bend and the size of the bounds; the horizontal distortion then scales each column of control points about its middle and the vertical distortion scales each row. The Warp effects and warp envelopes share the map, and content with no width or no height takes the middle of the patch along that side. New warps, the built-in graphic styles' Warps and warps opened from `.ai` files carry `version` 1 for it. Warps in `.vectorcraft` documents saved before it read as `version` 0 and keep their earlier look, and edits keep a warp's version; a `version` 0 warp saved to `.ai` opens again with `version` 1, since the file holds only its settings. The patches are VectorCraft's own rules; the styles and ranges are those of the Warp options in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (doc `live::tests::warp_nets_bend_each_style_as_its_own_patch`, `warp_net_arc_edges_are_concentric_circles`, `warp_net_distortion_scales_the_columns_then_the_rows`, `warp_net_takes_any_numbers`, `warp_net_bends_a_huge_box_without_overflowing`, `warp_envelopes_bend_flat_content_as_the_middle_of_the_patch`, `warp_envelopes_write_their_map_version_only_when_it_has_one`, `style_libs::tests::builtin_warp_styles_take_the_nets_map`; effects `tests::a_warp_draws_with_the_map_its_version_names`, `tests::a_warp_bends_a_flat_box_as_the_middle_of_its_patch`, `tests::new_warps_take_the_nets_version`; engine `effectedit::warps_keep_the_map_their_version_names`, `envelope::new_warp_envelopes_take_the_net_and_saved_ones_keep_their_map`; eps `ai_editing::tests::every_effect_a_graphic_style_holds_is_read_back`, `import::ai::tests::a_warp_envelope_opens_live`, `import::ai::tests::warp_envelopes_read_every_style`, `import::ai::style::tests::a_stack_of_fills_with_effects_of_their_own_is_read_as_itself`; ui-egui `dialogs::tests_warp::warp_options_edit_keeps_each_targets_map_version`). Scores and hours unchanged. - **Warp effects bend images:** a Warp effect on an image, or on a group that holds one, bends the image's pixels with its frame, as the Warp effect is documented to distort bitmap images in [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html): after the last effect, the image is cut into 10 × 10 cells of two triangles, each a clipped piece under its own affine map. Effects after the Warp reshape only the frame, a second Warp bends the same pieces, and warps saved without a version bend the pixels with their earlier map, as they bend the frame. A placed gradient on a group that holds the image follows the group's bounds as the pieces draw them. SVG writes the image once for the pieces; PDF, EPS, `.ai` and PNG write the bent pieces. The images stay unbent when their pieces would make the art pass 2 million objects, and so does an image whose frame keeps its shape past the anchor budget. A grayscale image's fill color now colorizes the pieces of a warp or an envelope, and an image under any geometry effect keeps that color and its smoothing setting. Existing documents with a Warp effect on an image, or on a group that holds one, draw differently: before, the image showed unbent, cut by the bent frame. So do existing documents with a colorized image under an envelope or a geometry effect, or an image drawn without smoothing under a geometry effect: before, those lost the color or the setting. The cell count and the limits are VectorCraft's own (effects `tests::warped_images_stay_within_the_object_budget`, `tests::warped_images_keep_document_keys_and_hidden_images_apart`, `tests::an_image_whose_frame_passes_the_budget_stays_whole`, `tests::effects_after_a_warp_reshape_an_images_frame_and_not_its_pieces`, `tests::an_images_pixels_take_the_map_their_warps_version_names`, `tests::an_image_under_a_geometry_effect_keeps_its_color_and_smoothing`, `tests::a_nested_groups_gradient_follows_its_warped_image`; engine `warp_images::an_images_pixels_bend_with_effect_warp`, `a_warped_image_keeps_its_bend_in_svg`, `a_warped_image_keeps_its_bend_in_pdf`, `a_warped_image_keeps_its_bend_in_ai`, `a_warped_image_keeps_its_bend_in_eps`, `a_warped_image_keeps_its_bend_in_png`, `svg_writes_an_image_clipped_twice_in_a_users_group_twice`, `expand_appearance_of_a_warped_image_draws_as_the_canvas_did`, `a_colorized_image_keeps_its_color_when_warped`, `a_warp_on_a_group_bends_the_image_in_it`, `envelope_distort::a_colorized_image_keeps_its_color_in_an_envelope`). Scores and hours unchanged. +- **`.ai` files keep an image's Warp live:** an embedded image whose appearance is one Warp effect, with no opacity mask, is saved to the `.ai` editing data with an art style of that Warp: its bent pieces are its drawn look, and the image itself follows on `%_` lines, as for other styled objects. Opening an `.ai` file reads such an image as the image with its Warp live, its pixels, placement, name and opacity kept, when the live warp draws as the file's drawn look and the import has a comparison left; otherwise the drawn look stays, with the drawn-look note. The Warp effect applies to bitmap images ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)), and native files keep live effects ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html)). A linked image with a Warp is saved as its drawn art, as before, and its live Warp is not saved. Images with an opacity mask, and images with a Warp and another effect or with another geometry effect, are saved and opened as their drawn art. Existing `.ai` files with an embedded image on `%_` lines open differently: before, that image also came in beside its drawn look. Which images keep the Warp and the comparison are VectorCraft's own rules (eps `ai_editing::tests::an_image_with_a_warp_reads_back_with_its_warp_live`, `an_image_whose_warp_draws_otherwise_than_its_look_keeps_its_look`, `an_image_on_hidden_lines_does_not_come_in_beside_its_look`, `other_warped_images_are_written_as_their_drawn_art`, `import::ai::read::ops::tests::an_image_takes_a_style_of_one_warp_alone`). Scores and hours unchanged. - **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged. - **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted, with Scale Strokes & Effects or Transform Patterns on too, and on each copy. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. The Gradient tool still shows a fitted gradient's vector at its unturned fit. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged.- **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. From 5700b0d8c111e985554d46dea28f96f793ccc6af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:30:43 -0800 Subject: [PATCH 19/28] Live Paint: the bucket shows a filled bucket over a face and a brush over an edge The Live Paint Bucket drew the crosshair in place of its own cursor. It now shows what a click paints: a filled paint bucket over a face it fills (of a Live Paint group, or a region of the selected paths), a brush over an edge it paints, and an empty bucket where it paints nothing. The cursor follows Paint Fills, Paint Strokes and Shift, and shows with Highlight off too. Alt still shows the Eyedropper, and Use Precise Cursors shows the crosshair. With a Live Paint group and ordinary paths selected, a region of the paths outside the group is now highlighted, as a click there fills it. The help page: https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html --- crates/engine/src/tests/prefs.rs | 3 + crates/tools/src/builder/live_paint.rs | 132 +++++++++++++++++++++---- crates/tools/src/builder/tests.rs | 101 ++++++++++++++++++- crates/tools/src/cursor.rs | 10 +- crates/tools/src/cursors.toml | 33 ++++++- crates/tools/src/lib.rs | 5 +- crates/ui-egui/src/canvas/cursor.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 3 + crates/ui-egui/src/cursors.rs | 43 +++++++- crates/ui-egui/src/cursors/tests.rs | 39 ++++++++ docs/target-app-parity.md | 12 +++ docs/ui-parity.md | 3 +- 12 files changed, 354 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 14669fd357..3da5f95b10 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -753,6 +753,9 @@ fn precise_cursors_replace_every_pen_state() { Cursor::ShapeBuilderErase, Cursor::AnchorPoint, Cursor::Curvature, + Cursor::LivePaintBucket, + Cursor::LivePaintBucketFace, + Cursor::LivePaintBucketEdge, ] { assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}"); } diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index 010e423743..2b6cef4532 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -49,6 +49,42 @@ fn lp_part_at<'a>(doc: &'a Document, p: Point, tol: f64, edge: bool, takes: &dyn best.map(|(_, g, e)| (g, Some(e))) } +/// The face and edge of a Live Paint group at `p`, among the groups `takes` takes, by the rules of +/// [`lp_part_at`], in one walk of the document. Inside a visible face of a group, the face is the +/// front-most such group's visible face under `p`, and with `edge` the edge is that group's visible +/// edge nearest `p` within `tol`. Outside every visible face there is no face, and with `edge` the +/// edge is the visible edge nearest `p` within `tol` among the groups (the front-most group's on a +/// tie). +fn lp_face_and_edge<'a>( + doc: &'a Document, + p: Point, + tol: f64, + edge: bool, + takes: &dyn Fn(NodeId) -> bool, +) -> (Option<&'a Arc>, Option<&'a Arc>) { + let mut in_face: Option<(&Arc, Option<&Arc>)> = None; + let mut best: Option<(f64, &Arc)> = None; + doc.walk(|n| { + if !is_live_paint(n) || !takes(n.id) { + return; + } + let near = if edge { visible_edge_near(n, p, tol) } else { None }; + if let Some(f) = visible_face_at(n, p) { + in_face = Some((f, near)); + } + if let Some(e) = near + && let Some((.., d)) = e.path_data().and_then(|pd| pd.nearest(p)) + && best.is_none_or(|b| d <= b.0) + { + best = Some((d, e)); + } + }); + match in_face { + Some((f, e)) => (Some(f), e), + None => (None, best.map(|b| b.1)), + } +} + /// Whether the Live Paint Bucket takes Live Paint group `id`: it is visible, with every layer and /// group around it. fn lp_visible(cx: &ToolContext, id: NodeId) -> bool { @@ -62,17 +98,25 @@ fn lp_selectable(cx: &ToolContext, id: NodeId) -> bool { cx.doc.is_editable(id) && crate::direct::in_scope(cx.doc, cx.isolation, id) } +/// Whether every selected object is a Live Paint group (true with nothing selected). A selection +/// that also holds other paths has regions outside its groups' faces that a click fills, making +/// one Live Paint group of the selection. +fn lp_sel_all_live(cx: &ToolContext) -> bool { + cx.selection.objects.iter().all(|id| cx.doc.node(*id).is_some_and(is_live_paint)) +} + /// What the Live Paint tools highlight at `p`: the part of a Live Paint group ([`lp_part_at`], among -/// the groups `takes` takes), else with `cache` the region of the selection under `p`. A large -/// selection's regions are found on another thread ([`RegionCache::ready`]), and until they are, no -/// region is highlighted. +/// the groups `takes` takes), else with `cache` the region of the selection under `p` when the +/// selection is not only Live Paint groups ([`lp_sel_all_live`]). A large selection's regions are +/// found on another thread ([`RegionCache::ready`]), and until they are, no region is highlighted. fn lp_hover(cx: &ToolContext, cache: Option<&mut RegionCache>, p: Point, edge: bool, takes: &dyn Fn(NodeId) -> bool) -> LpHover { if let Some((_, part)) = lp_part_at(cx.doc, p, cx.tol(4.0), edge, takes) { let path = part.and_then(|n| n.path_data()).map(|pd| pd.to_bezpath()); return path.map(|bp| if edge { LpHover::Edge(bp) } else { LpHover::Part(bp) }).unwrap_or_default(); } - let sel_is_live = cx.selection.objects.iter().any(|id| cx.doc.node(*id).is_some_and(is_live_paint)); - if !sel_is_live && let Some(i) = cache.and_then(|c| c.ready(cx, true)).and_then(|m| m.region_at(p)) { + if !lp_sel_all_live(cx) + && let Some(i) = cache.and_then(|c| c.ready(cx, true)).and_then(|m| m.region_at(p)) + { return LpHover::Region(i); } LpHover::None @@ -125,7 +169,8 @@ enum LpPaint { /// Shift-click fills the face. With both on, a click paints the edge nearest the pointer when one /// is within 4 pixels, else it fills the face, and Shift-click fills the face. With both off, a /// click paints nothing. With Highlight off, the face or edge under the pointer is not -/// highlighted. +/// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints +/// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper. pub struct LivePaintBucketTool { pub(super) cache: RegionCache, pub(super) hover: LpHover, @@ -202,21 +247,68 @@ impl LivePaintBucketTool { } /// The highlight at `p` for a pointer with Shift and Alt held as given: none with Alt or with - /// Highlight off, else the face or edge a click there paints. + /// Highlight off, else the face or edge a click there paints. With Highlight off the selection's + /// map is still made, for the cursor ([`Self::paints_at`]). fn hover_at(&mut self, cx: &ToolContext, p: Point, shift: bool, alt: bool) -> LpHover { - if alt || !self.highlight { + if alt { return LpHover::None; } - let takes = |id| lp_visible(cx, id); - match self.paints(shift) { - LpPaint::Nothing => LpHover::None, - LpPaint::Fills => lp_hover(cx, Some(&mut self.cache), p, false, &takes), - // A click paints no region of the selection, so none is highlighted. - LpPaint::Strokes => lp_hover(cx, None, p, true, &takes), - LpPaint::Both => match lp_part_at(cx.doc, p, cx.tol(4.0), true, &takes) { - Some((_, Some(e))) => e.path_data().map(|pd| LpHover::Edge(pd.to_bezpath())).unwrap_or_default(), - _ => lp_hover(cx, Some(&mut self.cache), p, false, &takes), - }, + let target = self.target_at(cx, p, shift); + if self.highlight { target } else { LpHover::None } + } + + /// What a click at `p` reaches, Shift held or not: whether it fills a face and paints an edge, + /// with the face and the edge of a Live Paint group there ([`lp_face_and_edge`]). The document + /// is walked once: the highlight and the cursor are asked for on every pointer update. + fn parts_at<'a>(&self, cx: &ToolContext<'a>, p: Point, shift: bool) -> (bool, Option<&'a Arc>, Option<&'a Arc>) { + let (wants_face, wants_edge) = match self.paints(shift) { + LpPaint::Nothing => return (false, None, None), + LpPaint::Fills => (true, false), + LpPaint::Strokes => (false, true), + LpPaint::Both => (true, true), + }; + let (face, edge) = lp_face_and_edge(cx.doc, p, cx.tol(4.0), wants_edge, &|id| lp_visible(cx, id)); + (wants_face, face, edge) + } + + /// The face or edge a click at `p` paints, Shift held or not. With Paint Strokes alone, a click + /// paints no region of the selection, so none is highlighted. + fn target_at(&mut self, cx: &ToolContext, p: Point, shift: bool) -> LpHover { + let (wants_face, face, edge) = self.parts_at(cx, p, shift); + let path = |n: &Arc| n.path_data().map(|pd| pd.to_bezpath()); + if let Some(e) = edge { + return path(e).map(LpHover::Edge).unwrap_or_default(); + } + if !wants_face { + return LpHover::None; + } + if let Some(f) = face { + return path(f).map(LpHover::Part).unwrap_or_default(); + } + if !lp_sel_all_live(cx) + && let Some(i) = self.cache.ready(cx, true).and_then(|m| m.region_at(p)) + { + return LpHover::Region(i); + } + LpHover::None + } + + /// The cursor for a click at `p`, Shift held or not: [`Cursor::LivePaintBucketEdge`] where it + /// paints an edge of a Live Paint group, [`Cursor::LivePaintBucketFace`] where it fills a face + /// of one or a region of the selected paths, else [`Cursor::LivePaintBucket`]. A region counts + /// once the selection's map is made (the pointer moving over it makes it), as it is highlighted. + fn paints_at(&self, cx: &ToolContext, p: Point, shift: bool) -> Cursor { + let (wants_face, face, edge) = self.parts_at(cx, p, shift); + let edge = edge.is_some(); + let region = + || !lp_sel_all_live(cx) && self.cache.key.as_ref() == Some(&RegionCache::key_for(cx, true)) && self.cache.map.region_at(p).is_some(); + let face = wants_face && !edge && (face.is_some() || region()); + if edge { + Cursor::LivePaintBucketEdge + } else if face { + Cursor::LivePaintBucketFace + } else { + Cursor::LivePaintBucket } } } @@ -315,8 +407,8 @@ impl Tool for LivePaintBucketTool { lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32) } - fn cursor(&self, _cx: &ToolContext, _p: Point, m: Mods) -> Cursor { - if m.alt { Cursor::Eyedropper } else { Cursor::LivePaintBucket } + fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor { + if m.alt { Cursor::Eyedropper } else { self.paints_at(cx, p, m.shift) } } fn options(&self) -> Value { diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index eeaf8f0ea7..89ce04eb3d 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1140,6 +1140,103 @@ fn bucket_options_choose_what_a_click_paints() { assert_eq!(t.options()["paintFills"], false); } +/// The cursor says what a click paints: a filled bucket over a face it fills, a brush over an +/// edge it paints, an empty bucket where it paints nothing, under each Paint Fills / Paint Strokes +/// setting and Shift; Alt keeps the Eyedropper, and Use Precise Cursors turns each into the +/// crosshair. +#[test] +fn bucket_cursor_shows_what_a_click_paints() { + let (d, ..) = live_group_doc(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let alt = Mods { alt: true, ..Default::default() }; + let at = |t: &LivePaintBucketTool, x: f64, m: Mods| t.cursor(&cx, Point::new(x, 25.0), m); + let (face, edge, none) = (Cursor::LivePaintBucketFace, Cursor::LivePaintBucketEdge, Cursor::LivePaintBucket); + let mut t = LivePaintBucketTool::default(); + // Paint Fills alone: the face, and with Shift the edge in reach. + assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default()), at(&t, 400.0, Mods::default())], [face, face, none]); + assert_eq!([at(&t, 51.0, shift), at(&t, 75.0, shift)], [edge, none]); + assert_eq!([at(&t, 51.0, alt), at(&t, 400.0, alt)], [Cursor::Eyedropper, Cursor::Eyedropper]); + // Paint Strokes alone: the edge in reach, nothing farther away; Shift fills the face. + t.set_option("paintFills", &json!(false)); + t.set_option("paintStrokes", &json!(true)); + assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default())], [edge, none]); + assert_eq!([at(&t, 51.0, shift), at(&t, 75.0, shift)], [face, face]); + // Both: the edge in reach, else the face; Shift fills the face. + t.set_option("paintFills", &json!(true)); + assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default()), at(&t, 400.0, Mods::default())], [edge, face, none]); + assert_eq!(at(&t, 51.0, shift), face); + // Both off: a click paints nothing. + t.set_option("paintFills", &json!(false)); + t.set_option("paintStrokes", &json!(false)); + assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, shift)], [none, none]); + // Highlight off: the cursor still says what a click paints. + let mut t = LivePaintBucketTool::default(); + t.set_option("highlight", &json!(false)); + assert_eq!([at(&t, 75.0, Mods::default()), at(&t, 51.0, shift)], [face, edge]); + for c in [face, edge, none] { + assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}"); + assert_eq!(c.stand_in(), None, "{c:?} is drawn"); + } +} + +/// Over a region of selected ordinary paths the cursor is the filled bucket once the pointer has +/// moved there (the move makes the selection's map), with Highlight on or off; with Paint Strokes +/// alone, a click there paints nothing and the bucket stays empty. +#[test] +fn bucket_cursor_fills_a_region_of_the_selected_paths() { + let (d, a, b) = two_rects(); + let mut s = Selection::default(); + s.set([a, b]); + let p = paint(); + let cx = cx(&d, &s, &p); + let pos = Point::new(75.0, 50.0); + for highlight in [true, false] { + let mut t = LivePaintBucketTool::default(); + t.set_option("highlight", &json!(highlight)); + assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket, "no map yet, highlight {highlight}"); + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0)); + t.poll(&cx, true); + assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace, "highlight {highlight}"); + assert_eq!(t.cursor(&cx, Point::new(400.0, 400.0), Mods::default()), Cursor::LivePaintBucket, "highlight {highlight}"); + t.set_option("paintFills", &json!(false)); + t.set_option("paintStrokes", &json!(true)); + assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket, "highlight {highlight}"); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty()); + } +} + +/// With a Live Paint group and ordinary paths selected, a region of the paths outside the group +/// is highlighted and shows the filled bucket, as a click there fills it; with only the group +/// selected, the same point shows the empty bucket. +#[test] +fn bucket_fills_a_region_of_a_selection_that_mixes_a_group_and_paths() { + let (mut d, a, b) = two_rects_at(200.0); + let (g, _) = live_square(&mut d, Rect::new(0.0, 0.0, 50.0, 50.0)); + let p = paint(); + let pos = Point::new(275.0, 50.0); + let mut s = Selection::default(); + s.set([g, a, b]); + let mixed = cx(&d, &s, &p); + let mut t = LivePaintBucketTool::default(); + t.pointer(&mixed, &ev(PointerKind::Move, pos.x, pos.y)); + t.poll(&mixed, true); + assert!(!t.overlays(&mixed).is_empty(), "the region is highlighted"); + assert_eq!(t.cursor(&mixed, pos, Mods::default()), Cursor::LivePaintBucketFace); + let acts = t.pointer(&mixed, &ev(PointerKind::Down, pos.x, pos.y)); + assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, v)] if id == "livePaint.fill" && v.get("ids").is_some()), "{acts:?}"); + let mut s = Selection::default(); + s.set([g]); + let live = cx(&d, &s, &p); + let mut t = LivePaintBucketTool::default(); + t.pointer(&live, &ev(PointerKind::Move, pos.x, pos.y)); + t.poll(&live, true); + assert!(t.overlays(&live).is_empty()); + assert_eq!(t.cursor(&live, pos, Mods::default()), Cursor::LivePaintBucket); +} + #[test] fn bucket_strokes_alone_paints_and_highlights_no_region_of_the_selection() { let (d, a, b) = two_rects(); @@ -1269,7 +1366,7 @@ fn bucket_alt_shift_samples_only_solid_color_and_restores_hover() { let alt = Mods { alt: true, ..Default::default() }; let both = Mods { alt: true, shift: true, ..Default::default() }; let pos = Point::new(75.0, 25.0); - assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket); + assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace); t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0)); assert!(!t.overlays(&cx).is_empty()); t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0).with_mods(alt)); @@ -1282,7 +1379,7 @@ fn bucket_alt_shift_samples_only_solid_color_and_restores_hover() { ); assert!(t.pointer(&cx, &ev(PointerKind::Down, 400.0, 400.0).with_mods(both)).is_empty()); t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0)); - assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket); + assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace); assert!(!t.overlays(&cx).is_empty()); } diff --git a/crates/tools/src/cursor.rs b/crates/tools/src/cursor.rs index a59bc28af0..d5cdd05bc5 100644 --- a/crates/tools/src/cursor.rs +++ b/crates/tools/src/cursor.rs @@ -141,8 +141,13 @@ pub enum Cursor { Knife, /// The Shaper tool. Shaper, - /// The Live Paint Bucket. + /// The Live Paint Bucket where a click paints nothing: an empty paint bucket. LivePaintBucket, + /// The Live Paint Bucket where a click fills a face (of a Live Paint group, or a region of + /// the selected paths): a filled paint bucket. + LivePaintBucketFace, + /// The Live Paint Bucket where a click paints an edge of a Live Paint group: a brush. + LivePaintBucketEdge, /// The Measure tool. Measure, /// The Print Tiling tool. @@ -280,6 +285,8 @@ impl Cursor { | Cursor::Knife | Cursor::Shaper | Cursor::LivePaintBucket + | Cursor::LivePaintBucketFace + | Cursor::LivePaintBucketEdge | Cursor::Measure | Cursor::PrintTiling | Cursor::SymbolSprayer @@ -320,7 +327,6 @@ impl Cursor { | Cursor::Join | Cursor::Knife | Cursor::Shaper - | Cursor::LivePaintBucket | Cursor::Measure | Cursor::ObjectsOnPath | Cursor::PrintTiling diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 362262b488..381eb5ed61 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -439,7 +439,10 @@ designer = false [[cursor]] id = "Eyedropper" group = "Colour and gradient" -shown_when = ["The Eyedropper tool, whatever the modifier keys. With Use Precise Cursors on, the crosshair shows instead."] +shown_when = [ + "The Eyedropper tool, whatever the modifier keys. With Use Precise Cursors on, the crosshair shows instead.", + "The Live Paint Bucket with Alt held (a click samples paint).", +] hotspot = "The pipette's tip." look = "A pipette." @@ -475,8 +478,32 @@ hotspot = "Where the mesh point goes." [[cursor]] id = "LivePaintBucket" group = "Colour and gradient" -shown_when = ["The Live Paint Bucket: a click fills a face (or an edge) of a Live Paint group."] -hotspot = "Where the paint pours out." +shown_when = [ + "The Live Paint Bucket where a click paints nothing: away from Live Paint groups and the selected paths' regions, or over a part the Paint Fills and Paint Strokes options (and Shift) leave unpainted.", + "With Use Precise Cursors on, the crosshair shows instead.", +] +hotspot = "The drop the paint pours onto." +look = "An empty paint bucket tipped toward the hotspot, a small drop on it. LivePaintBucketFace is the same bucket filled." + +[[cursor]] +id = "LivePaintBucketFace" +group = "Colour and gradient" +shown_when = [ + "The Live Paint Bucket over a face of a Live Paint group, or a region of the selected paths, that a click fills.", + "With Use Precise Cursors on, the crosshair shows instead.", +] +hotspot = "The drop the paint pours onto." +look = "LivePaintBucket filled, with a larger drop on the hotspot." + +[[cursor]] +id = "LivePaintBucketEdge" +group = "Colour and gradient" +shown_when = [ + "The Live Paint Bucket over an edge of a Live Paint group that a click paints with the stroke.", + "With Use Precise Cursors on, the crosshair shows instead.", +] +hotspot = "The brush's tip." +look = "A brush pointing down-left: bristles at the hotspot, then a white ferrule and a dark handle." # ── Width, blend, slice and shape builder ───────────────────────────────────────────────────────── diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index d73cd2297f..baf461c6c7 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -641,10 +641,11 @@ mod cursor_tests { ] { assert_eq!(cursor_at(id, &d, away), c, "{id}"); assert_eq!(c.precise(), Cursor::Crosshair, "{id}"); - // The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it. + // The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it. The + // Live Paint Bucket's bucket is drawn. let stand_in = match id { "mesh" => Some(Cursor::PenAdd), - "blobBrush" | "eraser" => None, + "blobBrush" | "eraser" | "livePaintBucket" => None, _ => Some(Cursor::Crosshair), }; assert_eq!(c.stand_in(), stand_in, "{id}"); diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index 71f70e455b..8b368fa496 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -123,6 +123,7 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon { Cursor::TypeArea | Cursor::TypeOnPath => C::Text, // The system has no tip outline to go round: its crosshair aims as well. Cursor::BlobBrush | Cursor::Eraser => C::Crosshair, + Cursor::LivePaintBucket | Cursor::LivePaintBucketFace | Cursor::LivePaintBucketEdge => C::Crosshair, // Not drawn yet: the cursor each borrows. Cursor::Lasso | Cursor::MagicWand @@ -133,7 +134,6 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon { | Cursor::Join | Cursor::Knife | Cursor::Shaper - | Cursor::LivePaintBucket | Cursor::Measure | Cursor::PrintTiling | Cursor::SymbolSprayer diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8597607717..6bf8a6fa97 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -184,6 +184,9 @@ fn system_cursors_show_the_same_crosshair_with_precise_cursors_on_or_off() { Cursor::PencilNew, Cursor::PencilStraight, Cursor::PencilContinue, + Cursor::LivePaintBucket, + Cursor::LivePaintBucketFace, + Cursor::LivePaintBucketEdge, ] { assert_eq!(cursor_icon(c), egui::CursorIcon::Crosshair, "{c:?}"); assert_eq!(cursor_icon(c), cursor_icon(c.precise()), "{c:?}"); diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index c26cae36ac..34156f2c41 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -432,6 +432,42 @@ fn shape_builder(p: &mut Ink, o: Pos2, erase: bool) { } } +/// The Live Paint Bucket: a paint bucket tipped toward the hotspot at its lower left, its mouth +/// down-left with a rim across it, and a drop on the hotspot. Empty (white) with a small drop where +/// a click paints nothing; filled, with a larger drop, where a click fills a face. +fn paint_bucket(p: &mut Ink, o: Pos2, filled: bool) { + // `u` runs from the hotspot up-right into the bucket, `v` across it. + let (d, n) = (vec2(1.0, -1.0).normalized(), vec2(1.0, 1.0).normalized()); + let at = |u: f32, v: f32| o + u * d + v * n; + poly(p, vec![at(5.5, -6.0), at(16.5, -4.5), at(16.5, 4.5), at(5.5, 6.0)], if filled { INK } else { HALO }, INK); + poly(p, vec![at(4.5, -7.0), at(6.5, -7.0), at(6.5, 7.0), at(4.5, 7.0)], INK, INK); + if filled { + p.circle_filled(o, 3.5, HALO); + p.circle_filled(o, 2.2, INK); + } else { + p.circle_filled(o, 2.5, HALO); + p.circle_filled(o, 1.25, INK); + } +} + +/// The Live Paint Bucket over an edge it paints: a brush, its bristles' tip on the hotspot, the +/// white ferrule and the black handle running up-right. +fn paint_brush(p: &mut Ink, o: Pos2) { + let (d, n) = (vec2(1.0, -1.0).normalized(), vec2(1.0, 1.0).normalized()); + let at = |u: f32, v: f32| o + u * d + v * n; + let bristles = vec![at(0.0, 0.0), at(4.0, -2.2), at(6.0, -2.2), at(6.0, 2.2), at(4.0, 2.2)]; + let ferrule = vec![at(6.0, -2.0), at(9.0, -2.0), at(9.0, 2.0), at(6.0, 2.0)]; + let handle = vec![at(9.0, -1.5), at(19.0, -1.2), at(19.0, 1.2), at(9.0, 1.5)]; + // Every halo first, so no part's halo covers another's outline. + for part in [&bristles, &ferrule, &handle] { + p.add(Shape::closed_line(part.clone(), Stroke::new(3.0, HALO))); + } + for (part, fill) in [(bristles, INK), (ferrule, HALO), (handle, INK)] { + p.add(Shape::convex_polygon(part.clone(), fill, Stroke::NONE)); + p.add(Shape::closed_line(part, Stroke::new(1.0, INK))); + } +} + /// The Hand tool and Space: an open hand (palm and four fingers, thumb to the left), or the same /// hand closed while it drags the view. Windows has no system hand that isn't a pointing finger /// (winit maps egui's Grab and Grabbing to the four-headed move cursor), so it is drawn like the @@ -480,7 +516,7 @@ fn magnifier(p: &mut Ink, o: Pos2, out: bool) { /// Every cursor with a glyph: its own, drawn here, or the one it borrows. #[cfg(test)] -const GLYPHS: [Cursor; 93] = [ +const GLYPHS: [Cursor; 95] = [ Cursor::Hand, Cursor::HandGrab, Cursor::ZoomIn, @@ -548,6 +584,8 @@ const GLYPHS: [Cursor; 93] = [ Cursor::Knife, Cursor::Shaper, Cursor::LivePaintBucket, + Cursor::LivePaintBucketFace, + Cursor::LivePaintBucketEdge, Cursor::Measure, Cursor::PrintTiling, Cursor::SymbolSprayer, @@ -669,6 +707,9 @@ fn glyph(c: Cursor, p: Pos2) -> Option> { Cursor::LoadedText => loaded_text(ink, p), Cursor::ShapeBuilder => shape_builder(ink, p, false), Cursor::ShapeBuilderErase => shape_builder(ink, p, true), + Cursor::LivePaintBucket => paint_bucket(ink, p, false), + Cursor::LivePaintBucketFace => paint_bucket(ink, p, true), + Cursor::LivePaintBucketEdge => paint_brush(ink, p), Cursor::Hand => hand(ink, p, false), Cursor::HandGrab => hand(ink, p, true), Cursor::ZoomIn => magnifier(ink, p, false), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 63ab6c23a1..4a12ff91b6 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -292,6 +292,45 @@ fn the_pencil_continuation_cursor_is_the_straight_line_cursor_with_an_end_point( } } +/// The Live Paint Bucket's cursors are drawn, not the crosshair: an empty bucket where a click +/// paints nothing, a filled bucket with a larger drop on the hotspot where it fills a face, and a +/// brush with its tip on the hotspot where it paints an edge. +#[test] +fn the_live_paint_bucket_shows_a_bucket_or_a_brush() { + for ppp in [1.0f32, 2.0] { + let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}")); + let (cross, empty, filled, brush) = + (img(Cursor::Crosshair), img(Cursor::LivePaintBucket), img(Cursor::LivePaintBucketFace), img(Cursor::LivePaintBucketEdge)); + // The pixel nearest the point `u` points up-right of the hotspot and `v` down-right across. + let at = |img: &CustomCursorImage, u: f32, v: f32| { + let s = std::f32::consts::FRAC_1_SQRT_2; + let [hx, hy] = img.hotspot.map(f32::from); + let (x, y) = ((hx + (u + v) * s * ppp - 0.5).round(), (hy + (v - u) * s * ppp - 0.5).round()); + let inside = x >= 0.0 && y >= 0.0 && x < f32::from(img.size[0]) && y < f32::from(img.size[1]); + if inside { pixel(img, x as usize, y as usize) } else { [0; 4] } + }; + let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64; + let white = |p: [u8; 4]| p[3] > 200 && p[0] > 192; + assert!(white(at(&empty, 11.0, 2.0)), "the empty bucket's body is white at {ppp}"); + assert!(inked(at(&filled, 11.0, 2.0)), "the filled bucket's body is ink at {ppp}"); + assert!(at(&empty, 0.0, 0.0)[3] > 0 && inked(at(&filled, 0.0, 0.0)), "a drop on the hotspot at {ppp}"); + if ppp == 2.0 { + assert!(inked(at(&filled, 1.4, 0.0)) && !inked(at(&empty, 2.0, 0.0)), "the filled bucket's drop is larger"); + } + assert!(inked(at(&brush, 3.0, 0.0)), "the bristles by the hotspot at {ppp}"); + assert!(white(at(&brush, 7.5, 0.0)), "the white ferrule at {ppp}"); + assert!(inked(at(&brush, 14.0, 0.0)), "the handle at {ppp}"); + assert!(!inked(at(&brush, 11.0, 4.0)), "the brush is thin where the bucket is wide at {ppp}"); + assert!(white(at(&empty, 14.0, 0.0)), "the empty bucket has no handle there at {ppp}"); + for (c, i) in [(Cursor::LivePaintBucket, &empty), (Cursor::LivePaintBucketFace, &filled), (Cursor::LivePaintBucketEdge, &brush)] { + assert!(c.stand_in().is_none(), "{c:?} is drawn"); + assert_ne!(i, &cross, "{c:?} is not the crosshair at {ppp}"); + assert_eq!(rasterize(c.precise(), ppp).as_ref(), Some(&cross), "{c:?} with Use Precise Cursors at {ppp}"); + } + assert!(empty != filled && filled != brush && empty != brush, "three looks at {ppp}"); + } +} + #[test] fn each_bitmap_is_made_once_so_the_os_cursor_is_kept() { let mut images = Images::default(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..f325fcad14 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2165,6 +2165,18 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s `live_paint_bucket_drag_rejects_invalid_points_atomically` covers invalid command input. Behaviour source: [Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html). Scores and estimates unchanged. +- **Live Paint Bucket cursors:** over a face a click fills (of a Live Paint group, or a region of + the selected paths) the cursor is a filled paint bucket, over an edge it paints it is a brush, + and where a click paints nothing it is an empty bucket. It follows Paint Fills, Paint Strokes + and Shift, and shows with Highlight off too; Alt still shows the Eyedropper, and Use Precise + Cursors shows the crosshair. The drawings are VectorCraft's own. With a Live Paint group and + ordinary paths selected, a region of the paths outside the group is highlighted and shows the + filled bucket, as a click there fills it. Tests: + `bucket_cursor_shows_what_a_click_paints`, `bucket_cursor_fills_a_region_of_the_selected_paths`, + `bucket_fills_a_region_of_a_selection_that_mixes_a_group_and_paths`, + `the_live_paint_bucket_shows_a_bucket_or_a_brush`. Behavior source: + [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html). + The cursor swatch preview is not built. Scores and estimates unchanged. ## Revision history diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5391e3dc5b..20c8721c72 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -161,7 +161,8 @@ tools, never checked side by side) isn't captured row by row. | Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | -| Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Live Paint Bucket, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | +| Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | +| Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | | Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | From 4282f4fa99f5e9f4a3f956fb863942f94afb5eea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:32:35 -0800 Subject: [PATCH 20/28] i18n: Document Info shows every category title and count label in the interface language Font Details, Linked Images and Embedded Images, and the Objects counts Compound Paths, Text Objects, Placed Documents, Symbol Instances, Gradient Meshes, Blends, Envelopes, Intertwine Groups, Opacity Masks and Objects with Effects had no catalog rows, so the panel and its category menu showed them in English in every other language. Each complete catalog now has them, and the Document rows Pattern Swatches (de, it, ja, ko, pl, uk, vi, zh-hant) and Path Length (bg, el) are added where missing. The catalog test now checks every category title, every Objects count label and Document's fixed row labels. document.info and the saved report keep the English labels. --- crates/engine/src/cmd.rs | 2 ++ crates/engine/src/cmd/docinfo.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/bs.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/ca.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/cs.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/da.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/de.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/el.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/es.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/fi.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/fr.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/hi.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/hu.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/id.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/it.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/ja.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/ka.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/ko.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/nl.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/pl.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/pt-br.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/ru.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/sv.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/tests.rs | 35 ++++++++++++++++++----------- crates/ui-egui/src/i18n/tr.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/uk.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/vi.tsv | 14 ++++++++++++ crates/ui-egui/src/i18n/zh-hans.tsv | 13 +++++++++++ crates/ui-egui/src/i18n/zh-hant.tsv | 14 ++++++++++++ docs/target-app-parity.md | 1 + 31 files changed, 387 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 80ed19d145..af768284b0 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -778,6 +778,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Document Info's category titles and the Objects category's count labels. +pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 833c7d22bf..a43325becd 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [ ]; /// The object counts of `document.info` and their labels. -const OBJECT_LABELS: [(&str, &str); 19] = [ +pub const OBJECT_LABELS: [(&str, &str); 19] = [ ("paths", "Paths"), ("compoundPaths", "Compound Paths"), ("groups", "Groups"), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..e41e163c62 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3369,6 +3369,20 @@ digits Malayalam Малаялам Spot Color Objects Обекти със спот цветове Pattern Objects Обекти с мостри Gradient Objects Обекти с градиенти + Font Details Подробности за шрифтовете + Linked Images Свързани изображения + Embedded Images Вградени изображения + Compound Paths Съставни пътища + Text Objects Текстови обекти + Placed Documents Поставени документи + Symbol Instances Екземпляри на символи + Gradient Meshes Мрежи с градиент + Blends Преливания + Envelopes Пликове + Intertwine Groups Групи с преплитане + Opacity Masks Маски за непрозрачност + Objects with Effects Обекти с ефекти + Path Length Дължина на пътя Spot Colors Спот цветове Spot Colors… Спот цветове… Spread: Разпространение: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..56c3ee508d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3954,6 +3954,19 @@ theme Appearance Izgled Spot Color Objects Objekti sa spot bojama Pattern Objects Objekti s uzorcima Gradient Objects Objekti s gradijentima + Font Details Detalji fontova + Linked Images Povezane slike + Embedded Images Ugrađene slike + Compound Paths Složene putanje + Text Objects Tekstualni objekti + Placed Documents Postavljeni dokumenti + Symbol Instances Instance simbola + Gradient Meshes Gradijentne mreže + Blends Stapanja + Envelopes Omotnice + Intertwine Groups Grupe isprepletanja + Opacity Masks Maske neprozirnosti + Objects with Effects Objekti s efektima Spot Colors Spot boje Spot Colors (0) Spot boje (0) Swatch Options Opcije uzorka boje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..50fc544253 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4379,6 +4379,19 @@ digits Malayalam Malaiàlam Spot Color Objects Objectes amb colors directes Pattern Objects Objectes amb motius Gradient Objects Objectes amb degradats + Font Details Detalls dels tipus de lletra + Linked Images Imatges enllaçades + Embedded Images Imatges incrustades + Compound Paths Traçats compostos + Text Objects Objectes de text + Placed Documents Documents col·locats + Symbol Instances Instàncies de símbol + Gradient Meshes Malles de degradat + Blends Fusions + Envelopes Embolcalls + Intertwine Groups Grups entrellaçats + Opacity Masks Màscares d’opacitat + Objects with Effects Objectes amb efectes Spot Colors Colors directes Spot Colors (0) Colors directes (0) Spot Colors… Colors directes… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..72e7a4bb0b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4010,6 +4010,19 @@ theme Appearance Motiv Spot Color Objects Objekty s přímými barvami Pattern Objects Objekty se vzorky Gradient Objects Objekty s přechody + Font Details Podrobnosti písem + Linked Images Propojené obrazy + Embedded Images Vložené obrazy + Compound Paths Složené cesty + Text Objects Textové objekty + Placed Documents Umístěné dokumenty + Symbol Instances Instance symbolů + Gradient Meshes Přechodové sítě + Blends Prolnutí + Envelopes Obálky + Intertwine Groups Skupiny proplétání + Opacity Masks Masky krytí + Objects with Effects Objekty s efekty Spot Colors Přímé barvy Spot Colors (0) Přímé barvy (0) Swatch Options Možnosti položky vzorníku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..92a7f74842 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3729,6 +3729,19 @@ theme Appearance Udseende Spot Color Objects Objekter med spotfarver Pattern Objects Objekter med mønstre Gradient Objects Objekter med gradienter + Font Details Skrifttypedetaljer + Linked Images Linkede billeder + Embedded Images Indlejrede billeder + Compound Paths Sammensatte kurver + Text Objects Tekstobjekter + Placed Documents Placerede dokumenter + Symbol Instances Symbolforekomster + Gradient Meshes Gradientnet + Blends Blandinger + Envelopes Konvolutter + Intertwine Groups Sammenfletningsgrupper + Opacity Masks Opacitetsmasker + Objects with Effects Objekter med effekter Spot Colors Spotfarver Spot Colors (0) Spotfarver (0) Swatch Options Indstillinger for farveprøve diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..e60fccea7b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3432,6 +3432,20 @@ effect Points Punkte Spot Color Objects Objekte mit Volltonfarben Pattern Objects Objekte mit Mustern Gradient Objects Objekte mit Verläufen + Font Details Schriftdetails + Linked Images Verknüpfte Bilder + Embedded Images Eingebettete Bilder + Compound Paths Zusammengesetzte Pfade + Text Objects Textobjekte + Placed Documents Platzierte Dokumente + Symbol Instances Symbolinstanzen + Gradient Meshes Verlaufsgitter + Blends Angleichungen + Envelopes Hüllen + Intertwine Groups Verflechtungsgruppen + Opacity Masks Deckkraftmasken + Objects with Effects Objekte mit Effekten + Pattern Swatches Musterfarbfelder Spot Colors Volltonfarben Spot Colors… Volltonfarben… Spread: Ausbreitung: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..a01fa440b2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3965,6 +3965,20 @@ digits Malayalam Μαλαγιάλαμ Spot Color Objects Αντικείμενα με χρώματα spot Pattern Objects Αντικείμενα με μοτίβα Gradient Objects Αντικείμενα με ντεγκραντέ + Font Details Λεπτομέρειες γραμματοσειρών + Linked Images Συνδεδεμένες εικόνες + Embedded Images Ενσωματωμένες εικόνες + Compound Paths Σύνθετες διαδρομές + Text Objects Αντικείμενα κειμένου + Placed Documents Τοποθετημένα έγγραφα + Symbol Instances Στιγμιότυπα συμβόλων + Gradient Meshes Πλέγματα ντεγκραντέ + Blends Αναμείξεις + Envelopes Περιβλήματα + Intertwine Groups Ομάδες διαπλοκής + Opacity Masks Μάσκες αδιαφάνειας + Objects with Effects Αντικείμενα με εφέ + Path Length Μήκος διαδρομής Spot Colors Πλακάτα χρώματα Spot Colors… Πλακάτα χρώματα… Stacked Bar Graph Tool Στοιβαγμένο ραβδόγραμμα (Stacked Bar Graph Tool) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..e1033c6d00 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3462,6 +3462,19 @@ digits Malayalam Malayálam Spot Color Objects Objetos con tintas planas Pattern Objects Objetos con motivos Gradient Objects Objetos con degradados + Font Details Detalles de fuentes + Linked Images Imágenes vinculadas + Embedded Images Imágenes incrustadas + Compound Paths Trazados compuestos + Text Objects Objetos de texto + Placed Documents Documentos colocados + Symbol Instances Instancias de símbolo + Gradient Meshes Mallas de degradado + Blends Fusiones + Envelopes Envolventes + Intertwine Groups Grupos entrelazados + Opacity Masks Máscaras de opacidad + Objects with Effects Objetos con efectos Spot Colors Tintas planas Spot Colors… Tintas planas… Spread: Extensión: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..273c789792 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3934,6 +3934,19 @@ theme Appearance Ulkoasu Spot Color Objects Objektit, joissa on spottivärejä Pattern Objects Objektit, joissa on kuvioita Gradient Objects Objektit, joissa on liukuvärejä + Font Details Fonttien tiedot + Linked Images Linkitetyt kuvat + Embedded Images Upotetut kuvat + Compound Paths Yhdistelmäpolut + Text Objects Tekstiobjektit + Placed Documents Sijoitetut asiakirjat + Symbol Instances Symbolien ilmentymät + Gradient Meshes Liukuväriverkot + Blends Sulautukset + Envelopes Vääristyskuoret + Intertwine Groups Lomitusryhmät + Opacity Masks Peittävyysmaskit + Objects with Effects Objektit, joissa on tehosteita Spot Colors Spottivärit Spot Colors (0) Spottivärit (0) Swatch Options Värimallin asetukset diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..38847af152 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3454,6 +3454,19 @@ digits Malayalam Malayalam Spot Color Objects Objets avec tons directs Pattern Objects Objets avec motifs Gradient Objects Objets avec dégradés + Font Details Détails des polices + Linked Images Images liées + Embedded Images Images incorporées + Compound Paths Tracés transparents + Text Objects Objets texte + Placed Documents Documents importés + Symbol Instances Instances de symbole + Gradient Meshes Filets de dégradé + Blends Dégradés de formes + Envelopes Enveloppes + Intertwine Groups Groupes entrelacés + Opacity Masks Masques d’opacité + Objects with Effects Objets avec effets Spot Colors Tons directs Spot Colors… Tons directs… Spread: Étendue : diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..c6c5c095e2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4741,6 +4741,19 @@ antiAlias Sharp शार्प Spot Color Objects स्पॉट कलर्स के साथ ऑब्जेक्ट्स Pattern Objects पैटर्न्स के साथ ऑब्जेक्ट्स Gradient Objects ग्रेडिएंट्स के साथ ऑब्जेक्ट्स + Font Details फ़ॉन्ट विवरण + Linked Images लिंक्ड चित्र + Embedded Images एम्बेडेड चित्र + Compound Paths कंपाउंड पाथ्स + Text Objects टेक्स्ट ऑब्जेक्ट्स + Placed Documents प्लेस्ड डॉक्यूमेंट्स + Symbol Instances सिंबल इंस्टेंस + Gradient Meshes ग्रेडिएंट मेश + Blends ब्लेंड्स + Envelopes एन्वेलप्स + Intertwine Groups इंटरट्वाइन समूह + Opacity Masks ओपेसिटी मास्क + Objects with Effects इफ़ेक्ट्स के साथ ऑब्जेक्ट्स Spot Colors स्पॉट रंग Spot Colors (0) स्पॉट कलर्स (0) Spot Colors… स्पॉट कलर्स… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..b215dc4a59 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4114,6 +4114,19 @@ mark-style Japanese Japán Spot Color Objects Direkt színeket használó objektumok Pattern Objects Mintázatokat használó objektumok Gradient Objects Színátmeneteket használó objektumok + Font Details Betűtípus-részletek + Linked Images Csatolt képek + Embedded Images Beágyazott képek + Compound Paths Összetett útvonalak + Text Objects Szövegobjektumok + Placed Documents Elhelyezett dokumentumok + Symbol Instances Szimbólumpéldányok + Gradient Meshes Színátmenetes hálók + Blends Összemosások + Envelopes Burkolók + Intertwine Groups Összefonási csoportok + Opacity Masks Átlátszósági maszkok + Objects with Effects Effektusokat használó objektumok Spot Colors Direktszínek Spot Colors (0) Direktszínek (0) Spot Colors… Direktszínek… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..6a04d2315b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3729,6 +3729,19 @@ theme Appearance Tampilan Spot Color Objects Objek dengan Warna Spot Pattern Objects Objek dengan Pola Gradient Objects Objek dengan Gradien + Font Details Detail Font + Linked Images Gambar Tertaut + Embedded Images Gambar Tersemat + Compound Paths Jalur Majemuk + Text Objects Objek Teks + Placed Documents Dokumen yang Ditempatkan + Symbol Instances Instans Simbol + Gradient Meshes Mesh Gradien + Blends Blend + Envelopes Amplop + Intertwine Groups Grup Jalinan + Opacity Masks Mask Opasitas + Objects with Effects Objek dengan Efek Spot Colors Warna spot Spot Colors (0) Warna spot (0) Swatch Options Opsi sampel diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..1ab5eb90f6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3507,6 +3507,20 @@ digits Malayalam Malayalam Spot Color Objects Oggetti con colori spot Pattern Objects Oggetti con motivi Gradient Objects Oggetti con sfumature + Font Details Dettagli font + Linked Images Immagini collegate + Embedded Images Immagini incorporate + Compound Paths Tracciati composti + Text Objects Oggetti di testo + Placed Documents Documenti inseriti + Symbol Instances Istanze di simbolo + Gradient Meshes Trame sfumatura + Blends Fusioni + Envelopes Involucri + Intertwine Groups Gruppi intrecciati + Opacity Masks Maschere di opacità + Objects with Effects Oggetti con effetti + Pattern Swatches Campioni motivo Spot Colors Colori spot Spot Colors… Colori spot… Spread: Estensione: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..91dbde618a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3284,6 +3284,20 @@ mark-style Japanese 日本式 Spot Color Objects 特色を使用したオブジェクト Pattern Objects パターンを使用したオブジェクト Gradient Objects グラデーションを使用したオブジェクト + Font Details フォントの詳細 + Linked Images リンク画像 + Embedded Images 埋め込み画像 + Compound Paths 複合パス + Text Objects テキストオブジェクト + Placed Documents 配置ドキュメント + Symbol Instances シンボルインスタンス + Gradient Meshes グラデーションメッシュ + Blends ブレンド + Envelopes エンベロープ + Intertwine Groups 織り交ぜグループ + Opacity Masks 不透明マスク + Objects with Effects 効果を使用したオブジェクト + Pattern Swatches パターンスウォッチ Spot Colors 特色 Spot Colors… 特色… Spread: 拡散: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..bf844b0007 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3568,6 +3568,19 @@ theme Appearance იერსახე Spot Color Objects ობიექტები სპოტ-ფერებით Pattern Objects ობიექტები პატერნებით Gradient Objects ობიექტები გრადიენტებით + Font Details შრიფტების დეტალები + Linked Images დაკავშირებული გამოსახულებები + Embedded Images ჩაშენებული გამოსახულებები + Compound Paths შედგენილი ტრაექტორიები + Text Objects ტექსტური ობიექტები + Placed Documents განთავსებული დოკუმენტები + Symbol Instances სიმბოლოს ეგზემპლარები + Gradient Meshes გრადიენტული ბადეები + Blends გადასვლები + Envelopes გარსები + Intertwine Groups გადახლართვის ჯგუფები + Opacity Masks გაუმჭვირვალობის ნიღბები + Objects with Effects ობიექტები ეფექტებით Spot Colors სპოტ-ფერები Swatch Options ფერის ნიმუშის პარამეტრები Ungroup Color Group ფერების ჯგუფის დაშლა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..767dc3382a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3273,6 +3273,20 @@ mark-style Japanese 일본식 Spot Color Objects 별색을 사용한 개체 Pattern Objects 패턴을 사용한 개체 Gradient Objects 그레이디언트를 사용한 개체 + Font Details 글꼴 세부 정보 + Linked Images 연결된 이미지 + Embedded Images 포함된 이미지 + Compound Paths 컴파운드 패스 + Text Objects 텍스트 개체 + Placed Documents 가져온 문서 + Symbol Instances 심볼 인스턴스 + Gradient Meshes 그레이디언트 메시 + Blends 블렌드 + Envelopes 엔벨로프 + Intertwine Groups 교차 그룹 + Opacity Masks 불투명 마스크 + Objects with Effects 효과를 사용한 개체 + Pattern Swatches 패턴 견본 Spot Colors 별색 Spot Colors… 별색… Spread: 확산: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..ec4c063db7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3743,6 +3743,19 @@ theme Appearance Vormgeving Spot Color Objects Objecten met spotkleuren Pattern Objects Objecten met patronen Gradient Objects Objecten met verlopen + Font Details Lettertypedetails + Linked Images Gekoppelde afbeeldingen + Embedded Images Ingesloten afbeeldingen + Compound Paths Samengestelde paden + Text Objects Tekstobjecten + Placed Documents Geplaatste documenten + Symbol Instances Symboolinstanties + Gradient Meshes Verlooprasters + Blends Vermengingen + Envelopes Omvormingen + Intertwine Groups Verstrengelingsgroepen + Opacity Masks Dekkingmaskers + Objects with Effects Objecten met effecten Spot Colors Spotkleuren Spot Colors (0) Spotkleuren (0) Swatch Options Kleurstaalopties diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..b0f6b4c37d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3869,6 +3869,20 @@ theme Appearance Wygląd Spot Color Objects Obiekty z kolorami dodatkowymi Pattern Objects Obiekty ze wzorkami Gradient Objects Obiekty z gradientami + Font Details Szczegóły czcionek + Linked Images Połączone obrazy + Embedded Images Osadzone obrazy + Compound Paths Ścieżki złożone + Text Objects Obiekty tekstowe + Placed Documents Umieszczone dokumenty + Symbol Instances Wystąpienia symboli + Gradient Meshes Siatki gradientowe + Blends Przejścia + Envelopes Koperty + Intertwine Groups Grupy przeplatania + Opacity Masks Maski krycia + Objects with Effects Obiekty z efektami + Pattern Swatches Próbki wzorków Spot Colors Kolory dodatkowe Swatch Options Opcje próbki Ungroup Color Group Rozgrupuj grupę kolorów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..513616bf90 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2910,6 +2910,19 @@ digits Malayalam Malaiala Spot Color Objects Objetos com cores spot Pattern Objects Objetos com padrões Gradient Objects Objetos com gradientes + Font Details Detalhes das fontes + Linked Images Imagens vinculadas + Embedded Images Imagens incorporadas + Compound Paths Caminhos compostos + Text Objects Objetos de texto + Placed Documents Documentos colocados + Symbol Instances Instâncias de símbolo + Gradient Meshes Malhas de gradiente + Blends Mesclagens + Envelopes Envelopes + Intertwine Groups Grupos entrelaçados + Opacity Masks Máscaras de opacidade + Objects with Effects Objetos com efeitos Spot Colors Cores Spot Spot Colors… Cores Spot… Spread: Propagação: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..91c1580abf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3494,6 +3494,19 @@ digits Malayalam Малаялам Spot Color Objects Объекты с плашечными цветами Pattern Objects Объекты с узорами Gradient Objects Объекты с градиентами + Font Details Сведения о шрифтах + Linked Images Связанные изображения + Embedded Images Внедрённые изображения + Compound Paths Составные контуры + Text Objects Текстовые объекты + Placed Documents Размещённые документы + Symbol Instances Экземпляры символов + Gradient Meshes Градиентные сетки + Blends Переходы + Envelopes Оболочки + Intertwine Groups Группы переплетения + Opacity Masks Непрозрачные маски + Objects with Effects Объекты с эффектами Spot Colors Плашечные цвета Spot Colors… Плашечные цвета… Spread: Разворот: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..a2e0b53a13 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3384,6 +3384,19 @@ digits Malayalam Malayalam Spot Color Objects Objekt med dekorfärger Pattern Objects Objekt med mönster Gradient Objects Objekt med gradienter + Font Details Typsnittsdetaljer + Linked Images Länkade bilder + Embedded Images Inbäddade bilder + Compound Paths Sammansatta banor + Text Objects Textobjekt + Placed Documents Placerade dokument + Symbol Instances Symbolinstanser + Gradient Meshes Gradientnät + Blends Blandningar + Envelopes Kuvert + Intertwine Groups Sammanflätningsgrupper + Opacity Masks Opacitetsmasker + Objects with Effects Objekt med effekter Spot Colors Dekorfärger Spot Colors… Dekorfärger… Spread: Spridning: diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 66caa1c3a4..364981e5b8 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -239,24 +239,33 @@ fn control_bar_panel_menu_labels_are_in_complete_catalogs() { } } -/// The titles of Document Info's Spot Color Objects, Pattern Objects and Gradient Objects -/// categories, which the panel, its menu and the Objects category's counts show. +/// Document Info's labels: every category title, which the panel and its menu show, every count +/// label of the Objects category, and the Document category's fixed row labels (the artboard rows +/// show artboard names and are left out). #[test] -fn document_info_object_category_titles_are_in_complete_catalogs() { +fn document_info_labels_are_in_complete_catalogs() { let mut session = vectorcraft_engine::Session::new(); session.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap(); + session.execute("shape.rectangle", &serde_json::json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); let info = session.execute("document.info", &serde_json::json!({})).unwrap(); - let titles: Vec<&str> = info["sections"] - .as_array() - .unwrap() - .iter() - .filter(|s| matches!(s["id"].as_str(), Some("spotColors" | "patterns" | "gradients"))) - .filter_map(|s| s["title"].as_str()) - .collect(); - assert_eq!(titles, ["Spot Color Objects", "Pattern Objects", "Gradient Objects"]); + let sections = info["sections"].as_array().unwrap(); + let titles: Vec<&str> = sections.iter().filter_map(|s| s["title"].as_str()).collect(); + let categories: Vec<&str> = vectorcraft_engine::cmd::CATEGORIES.iter().map(|&(_, title)| title).collect(); + assert_eq!(titles, categories); + let mut labels = categories; + labels.extend(vectorcraft_engine::cmd::OBJECT_LABELS.iter().map(|&(_, label)| label)); + let objects = sections.iter().find(|s| s["id"] == "objects").unwrap()["rows"].as_array().unwrap(); + assert!(objects.iter().any(|r| r[0] == "Path Length"), "{objects:?}"); + labels.push("Path Length"); + let document = sections.iter().find(|s| s["id"] == "document").unwrap()["rows"].as_array().unwrap(); + let artboards = document.iter().position(|r| r[0] == "Artboards").unwrap(); + let names = artboards + 1..=artboards + document[artboards][1].as_str().unwrap().parse::().unwrap(); + let fixed: Vec<&str> = document.iter().enumerate().filter(|(k, _)| !names.contains(k)).filter_map(|(_, r)| r[0].as_str()).collect(); + assert_eq!(fixed.len(), 9, "{fixed:?}"); + labels.extend(fixed); for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { - for title in &titles { - assert!(lang.catalog().plain(title).is_some(), "{} is missing {title}", lang.code); + for label in &labels { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); } } } diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..afd3b904a9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3283,6 +3283,19 @@ digits Malayalam Malayalam Spot Color Objects Spot Renkli Nesneler Pattern Objects Desenli Nesneler Gradient Objects Degradeli Nesneler + Font Details Yazı Tipi Ayrıntıları + Linked Images Bağlantılı Görseller + Embedded Images Gömülü Görseller + Compound Paths Bileşik Yollar + Text Objects Metin Nesneleri + Placed Documents Yerleştirilen Belgeler + Symbol Instances Sembol Örnekleri + Gradient Meshes Degrade Örgüler + Blends Karışımlar + Envelopes Zarflar + Intertwine Groups İç İçe Geçme Grupları + Opacity Masks Opaklık Maskeleri + Objects with Effects Efektli Nesneler Spot Colors Nokta Renkleri Spot Colors… Nokta Renkleri… Spread: Yayılma: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..24556a72e2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3500,6 +3500,20 @@ effect Points Точки Spot Color Objects Об’єкти з плашковими кольорами Pattern Objects Об’єкти з візерунками Gradient Objects Об’єкти з градієнтами + Font Details Відомості про шрифти + Linked Images Пов’язані зображення + Embedded Images Впроваджені зображення + Compound Paths Складені контури + Text Objects Текстові об’єкти + Placed Documents Розміщені документи + Symbol Instances Екземпляри символів + Gradient Meshes Градієнтні сітки + Blends Переходи + Envelopes Оболонки + Intertwine Groups Групи переплетення + Opacity Masks Маски непрозорості + Objects with Effects Об’єкти з ефектами + Pattern Swatches Зразки візерунків Spot Colors Плашкові кольори Spot Colors… Плашкові кольори… Spread: Розворот: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..f53e50f021 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3846,6 +3846,20 @@ mark-style Japanese Kiểu Nhật Spot Color Objects Đối tượng có màu đặc biệt Pattern Objects Đối tượng có họa tiết Gradient Objects Đối tượng có chuyển sắc + Font Details Chi tiết phông chữ + Linked Images Hình ảnh đã liên kết + Embedded Images Hình ảnh đã nhúng + Compound Paths Đường dẫn phức + Text Objects Đối tượng văn bản + Placed Documents Tài liệu đã đặt + Symbol Instances Thực thể ký hiệu + Gradient Meshes Lưới chuyển sắc + Blends Hòa trộn + Envelopes Envelope + Intertwine Groups Nhóm đan xen + Opacity Masks Mặt nạ độ mờ + Objects with Effects Đối tượng có hiệu ứng + Pattern Swatches Mẫu màu họa tiết Spot Colors Màu đặc biệt Spot Colors… Màu đặc biệt… Spray Radius Bán kính phun diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..5141eaa16d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3323,6 +3323,19 @@ digits Malayalam 马拉雅拉姆数字 Spot Color Objects 使用专色的对象 Pattern Objects 使用图案的对象 Gradient Objects 使用渐变的对象 + Font Details 字体详细信息 + Linked Images 链接的图像 + Embedded Images 嵌入的图像 + Compound Paths 复合路径 + Text Objects 文本对象 + Placed Documents 置入的文档 + Symbol Instances 符号实例 + Gradient Meshes 渐变网格 + Blends 混合 + Envelopes 封套 + Intertwine Groups 交织编组 + Opacity Masks 不透明度蒙版 + Objects with Effects 使用效果的对象 Spot Colors 专色 Spot Colors… 专色… Spread: 扩散: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..f01e340aba 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4559,6 +4559,20 @@ digits Malayalam 馬來亞拉姆數字 Spot Color Objects 使用特別色的物件 Pattern Objects 使用圖樣的物件 Gradient Objects 使用漸層的物件 + Font Details 字體詳細資訊 + Linked Images 已連結的影像 + Embedded Images 嵌入的影像 + Compound Paths 複合路徑 + Text Objects 文字物件 + Placed Documents 已置入的文件 + Symbol Instances 符號範例 + Gradient Meshes 漸層網格 + Blends 漸變 + Envelopes 封套 + Intertwine Groups 交織群組 + Opacity Masks 不透明度遮色片 + Objects with Effects 使用效果的物件 + Pattern Swatches 圖樣色票 Spot Colors 特別色 Spot Colors… 特別色… Spread: 擴散: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..08234ac269 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1437,6 +1437,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Document Info's Gradient Objects category lists the objects whose fill or stroke is a gradient, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as the count of objects with gradient fills or strokes. Each object is listed by name with the gradients it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "gradients"}`, `gradientObjects`). Naming a linked gradient by its swatch and any other gradient by its kind, and leaving out paint that draws nothing by the rules Pattern Objects follows, gradient swatches no art uses, gradient meshes and gradients drawn by effects, are VectorCraft's own rules. Objects counts the listed objects as Gradient Objects. Test: `cmd::docinfo::tests::info_lists_the_gradient_objects` (vectorcraft-engine). Document Info's Spot Color Objects category lists the objects that use spot colors, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as objects using spot color separations. Each object is listed by name with the spot colors it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "spotColors"}`, `spotObjects`). Taking a solid color or a gradient stop linked to a spot swatch at a tint above 0 and a grayscale image colorized with one, leaving out process colors that look the same, Registration, gradients whose stops are all at an opacity of 0, fills and strokes at an opacity of 0, paint that draws nothing by the rules Pattern Objects follows, spot swatches no art uses and spot colors inside patterns, symbols, opacity masks, effects and placed files, are VectorCraft's own rules. Objects counts the listed objects as Spot Color Objects. Tests: `cmd::docinfo::tests::info_lists_the_spot_color_objects`, `spot_color_objects_take_colorized_images_and_skip_clear_gradients` and `spot_color_objects_skip_clear_fills_and_strokes` (vectorcraft-engine). Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. + Document Info's category menu and headings show every category title in the interface language, Font Details, Linked Images and Embedded Images included, and the Objects category shows every count label in it too: Compound Paths, Text Objects, Placed Documents, Symbol Instances, Gradient Meshes, Blends, Envelopes, Intertwine Groups, Opacity Masks and Objects with Effects. The Document category's Pattern Swatches row and the Objects category's Path Length row are translated in every catalog that has every menu label. `document.info` and the saved report keep the English labels. Showing these labels in the interface language is VectorCraft's own rule. Test: `i18n::tests::document_info_labels_are_in_complete_catalogs` (vectorcraft-ui-egui). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). A rename in Brush Options and Delete Brush change every stroke that paints with the brush: in the layers and opacity masks, symbols, graph designs, pattern tiles, graphic styles and the art of other brushes. A rename gives those strokes the new name, and Delete Brush makes them plain strokes, in one undo step. A scatter, art or pattern brush dragged from the Brushes panel onto an empty part of the canvas places a copy of its art there to edit, as the [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html) page describes (`brush.placeArt`). The copy is centered where it is dropped. A pattern brush comes out as its tiles in a row, 10 pt apart, each in a group named for its tile, with an unpainted rectangle at the back of a tile that has a repeat frame. The centering and the tile layout are VectorCraft's own rules. Evidence: `tests::brushsym::place_art_puts_a_copy_of_the_brush_art_where_it_is_dropped`, `tests::brushsym::pattern_brushes_place_their_tiles_in_a_row` (vectorcraft-engine), `canvas::tests::a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there` (vectorcraft-ui-egui). From 57d37a6dae48fdc0231dbd8f7ed14df0575a1558 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:23:42 -0800 Subject: [PATCH 21/28] 3D: fill walls and gapped strokes draw in depth order where they overlap Extrude & Bevel, Extrude & Bevel (Classic) and Inflate sorted the fill walls and the faces of a stroke that leaves gaps (dashed, profiled, brushed) by one depth each, so a far stroke face could draw over a near fill wall and the reverse. Two such strokes on one shape drew over each other the same way, and Inflate drew a plain stroke as if it covered the fill's edge, which an inflated fill can rise in front of. - Each flat facet now carries its plane, so its depth can be measured at any point under it, with orthographic and perspective views. - Where faces of one shape's fill and strokes overlap in the wrong order, the overlapping faces are ordered by their depths where they overlap. A fill wall and its covering stroke keep their order. - A face of a stroke that leaves gaps that passes through a fill wall, a covering stroke's face or an earlier such stroke's face is cut along the line where their depths meet, keeping its curved outline, within the face limit and the paint allowance. - Under Inflate, no stroke counts as covering the fill's edge. - The faces go in one order when the fill and strokes are at full opacity with Normal blending. A member of a 3D group with an opacity mask or a blending mode of its own orders its faces inside it when its own paints qualify. A gradient with transparent stops keeps the one order with graphics on its cap, and so does Inflate in gradients under a colored light. A solid color under a colored light, drawn as one composite per surface, still draws each surface whole. --- crates/effects/src/revolve.rs | 2 +- crates/effects/src/solids.rs | 625 ++++++++++++++++++-- crates/effects/src/solids/tests.rs | 436 ++++++++++++++ crates/effects/src/solids/tests_graphics.rs | 104 ++++ crates/three-d/src/lib.rs | 4 +- crates/three-d/src/solid.rs | 42 ++ crates/three-d/src/solid/build.rs | 10 +- crates/three-d/src/solid/tests.rs | 23 + docs/target-app-parity.md | 1 + docs/three-d.md | 19 +- 10 files changed, 1202 insertions(+), 64 deletions(-) diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index e9d64864d0..1677937f17 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -27,7 +27,7 @@ pub fn is_revolve(id: &str) -> bool { /// Most bytes the copies of the object's paint in the faces may take together. Each face and the /// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of /// thousands of faces took gigabytes; past this the source path is drawn. -const MAX_PAINT_COPIES: usize = 256 << 20; +pub(crate) const MAX_PAINT_COPIES: usize = 256 << 20; /// The most face and box tests a group's transparent members' faces take together to rejoin their /// members' last runs; past them each starts a run of its own. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 52739983a5..bd1e6e34ae 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -5,8 +5,9 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer}; -use vectorcraft_geom::{FillRule, PathData, Rect}; -use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View}; +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2}; +use vectorcraft_pathops::BoolOp; +use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View}; #[cfg(test)] use vectorcraft_doc::color::Color; @@ -678,7 +679,8 @@ fn built_solids<'a>( /// What a face of one of the solids [`art_for`] draws in one order was built from: the facet's /// depth, whether it is a side face and whether it is turned away from the viewer, the bounds of /// its polygon, the index of its shape, and whether its solid is that shape's fill or one of its -/// strokes that covers the fill's whole edge. +/// strokes that covers the fill's whole edge. A face that [`convex_face`] takes also keeps its +/// polygon and plane, for [`local_order`]; every other face has an empty `outline` and no `plane`. struct Placed { depth: f64, side: bool, @@ -686,6 +688,8 @@ struct Placed { bounds: Rect, member: usize, paints: Paints, + outline: Vec, + plane: Option, } /// The part of its shape a face's solid is built from ([`Placed`]). @@ -694,13 +698,22 @@ enum Paints { Fill, /// A stroke whose solid holds the fill's whole edge and hides it: one with a width, without /// dashes, a width profile or a brush, painted with a solid color or a gradient without - /// transparent stops, on a shape whose subpaths are all closed. + /// transparent stops, on a shape whose subpaths are all closed, extruded (an inflated fill can + /// rise in front of its stroke). Stroke, Other, } +/// Can a stroke's solid on a shape with outline `path` hold the fill's edge ([`Paints::Stroke`]) +/// under the effect `effect`? Only when the subpaths are all closed and the effect extrudes: an +/// inflated fill can rise in front of its stroke. +fn holds_edge(effect: &str, path: &PathData) -> bool { + effect != INFLATE && path.subpaths.iter().all(|p| p.closed) +} + impl Paints { - /// What `item` of a shape is, the shape's subpaths all closed when `closed`. + /// What `item` of a shape is, its stroke's solid able to hold the fill's edge when `closed` + /// ([`holds_edge`]). fn of(item: &AppearanceItem, closed: bool) -> Self { match item { AppearanceItem::Fill(_) => Paints::Fill, @@ -729,10 +742,434 @@ impl Placed { fn of(f: &Facet, member: usize, paints: Paints) -> Self { let mut points = f.contours.iter().flatten(); let bounds = points.next().map_or(Rect::ZERO, |p| points.fold(Rect::from_points(*p, *p), |r, q| r.union_pt(*q))); - Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints } + let local = convex_face(f).is_some(); + let outline = f.contours.first().filter(|_| local).cloned().unwrap_or_default(); + let plane = f.plane.filter(|_| local); + Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints, outline, plane } } } +/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares; +/// the pairs they have not reached by then keep the order of their depths. +const MAX_LOCAL_CHECKS: usize = 4_000_000; + +/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other +/// than a planar end, with a plane and one convex contour: a face [`local_order`] and +/// [`cut_stroke_faces`] work on. +fn convex_face(f: &Facet) -> Option<(&[Point], f64)> { + if f.away || f.end.is_some() || f.plane.is_none() || f.contours.len() != 1 { + return None; + } + let c = f.contours.first()?; + Some((c, convex(c)?)) +} + +/// The bounds of polygon `p` (`Rect::ZERO` when it has no points). +fn polygon_bounds(p: &[Point]) -> Rect { + let mut points = p.iter(); + points.next().map_or(Rect::ZERO, |q| points.fold(Rect::from_points(*q, *q), |r, q| r.union_pt(*q))) +} + +/// Do rectangles `a` and `b` overlap (more than along an edge)? +fn rects_overlap(a: Rect, b: Rect) -> bool { + a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1 +} + +/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces +/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within +/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies +/// of the costliest stroke's paint. +fn cut_room<'a>(items: impl Iterator, faces: usize, paint_bytes: usize) -> usize { + let per_face = items + .filter(|item| matches!(item, AppearanceItem::Stroke(_))) + .map(|item| { + let mut copies = 0usize; + crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item)); + copies + }) + .max() + .unwrap_or(0) + .max(1); + let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face; + MAX_OBJECT_FACES.saturating_sub(faces).min(affordable) +} + +/// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a +/// stroke that does not cover the fill's edge ([`Paints::Other`]) that passes through the plane of a +/// face of the same shape's fill, or of a face of another of the shape's strokes, where the two +/// overlap on the drawing ([`cut_through`]). Of two such strokes, the later one's faces are cut +/// against the earlier one's; a covering stroke's faces ([`Paints::Stroke`]) are never cut, and an +/// other stroke's faces are cut against them. At most `room` pieces are added, the object's solids +/// together. +fn cut_stroke_faces(solids: &mut [(Paints, usize, &mut Vec)], mut room: usize) { + let mut checks = 0usize; + for k in 0..solids.len() { + let Some((Paints::Other, shape)) = solids.get(k).map(|(p, s, _)| (*p, *s)) else { continue }; + let walls: Vec = (0..solids.len()) + .filter(|&j| { + solids.get(j).is_some_and(|(p, s, _)| { + *s == shape + && match p { + Paints::Fill | Paints::Stroke => true, + Paints::Other => j < k, + } + }) + }) + .collect(); + for j in walls { + let (wall, stroke) = if j < k { + let (before, from) = solids.split_at_mut(k); + (&**before[j].2, &mut *from[0].2) + } else { + let (before, from) = solids.split_at_mut(j); + (&**from[0].2, &mut *before[k].2) + }; + cut_through(wall, stroke, &mut room, &mut checks); + } + } +} + +/// Cut each face of `stroke` that passes through the plane of a face of `solid` (the fill's or +/// another stroke's) where their polygons overlap on the drawing, along the line where their depths +/// meet, so that each piece is wholly in front of or behind that face there ([`local_order`] can +/// then order them). A dash's end, which crosses the edge of the fill it is drawn on, is cut into its +/// part outside the fill, in front of the fill's wall, and its part inside, behind it. A piece keeps +/// the part of the face's curved outline on its side of the cut. The first piece of a face takes its +/// place, the others go at the end. Each cut adds a face out of `room`, and each pair compared counts +/// in `checks` ([`MAX_LOCAL_CHECKS`]); cutting stops when either runs out. +fn cut_through(solid: &[Facet], stroke: &mut Vec, room: &mut usize, checks: &mut usize) { + // The faces from left to right: a face is compared with those that start left of its end. + let mut walls: Vec<(&Facet, &[Point], f64, Rect)> = + solid.iter().filter_map(|f| convex_face(f).map(|(c, turn)| (f, c, turn, polygon_bounds(c)))).collect(); + if walls.is_empty() { + return; + } + walls.sort_by(|a, b| a.3.x0.total_cmp(&b.3.x0)); + let mut k = 0; + while k < stroke.len() { + let mut extent = stroke.get(k).and_then(convex_face).map(|(c, _)| polygon_bounds(c)); + for &(wall, outline, turn, bounds) in &walls { + let Some(at) = extent.filter(|e| bounds.x0 < e.x1) else { break }; + if *checks >= MAX_LOCAL_CHECKS || *room == 0 { + return; + } + *checks += 1; + if !rects_overlap(at, bounds) { + continue; + } + let Some(s) = stroke.get(k) else { break }; + let Some((c, _)) = convex_face(s) else { break }; + if let Some((near, far)) = cut(s, c, wall, outline, turn) { + *room -= 1; + extent = convex_face(&near).map(|(c, _)| polygon_bounds(c)); + stroke[k] = near; + stroke.push(far); + } + } + k += 1; + } +} + +/// Face `s` (polygon `c`) cut where its depth meets that of face `wall` (convex polygon `outline`, +/// turning with sign `turn`): its piece nearer the viewer than the wall's plane and its piece +/// farther. `None` when the two do not overlap on the drawing or `s` is on one side of the wall's +/// plane wherever they do. +fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Option<(Facet, Facet)> { + let ahead = |p: Point| Some(s.depth_at(p)? - wall.depth_at(p)?); + let overlap = clip_convex(c, outline, turn); + centroid(&overlap)?; + let tolerance = 1e-6; + let (mut nearer, mut farther) = (false, false); + for p in &overlap { + let d = ahead(*p)?; + nearer |= d > tolerance; + farther |= d < -tolerance; + } + if !(nearer && farther) { + return None; + } + let (a, b) = (s.plane?, wall.plane?); + let values: Vec = match (a.eye, b.eye) { + (Some(e), Some(f)) if e == f && a.center == b.center => { + // With perspective the depths themselves are not linear on the drawing, but where they + // meet is a line: (dA - aA e)(nzB - aB) = (dB - aB e)(nzA - aA), with aX = (nX · p) / e, + // whose difference is linear. Its sign is that of the depths' difference over the + // product of the two denominators, taken at the middle of the face. + let at = |p: Point| { + let (x, y) = (p.x - a.center.x, p.y - a.center.y); + let (aa, ab) = ((a.normal[0] * x + a.normal[1] * y) / e, (b.normal[0] * x + b.normal[1] * y) / e); + let (da, db) = (a.normal[2] - aa, b.normal[2] - ab); + ((a.offset - aa * e) * db - (b.offset - ab * e) * da, da * db) + }; + let sign = at(centroid(c)?).1.signum(); + c.iter().map(|p| at(*p).0 * sign).collect() + } + _ => c.iter().map(|p| ahead(*p)).collect::>()?, + }; + let piece = |sign: f64| { + let points = half(c, &values, sign); + let mid = centroid(&points)?; + let mut f = s.clone(); + f.depth = s.depth_at(mid).unwrap_or(s.depth); + f.contours = vec![points]; + f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign)); + Some(f) + }; + Some((piece(1.0)?, piece(-1.0)?)) +} + +/// Curved outline `outline` of a face with polygon `c`, cut along the line where `values` (one per +/// point of `c`, varying linearly along each edge) is 0, keeping the side where `sign` times them is +/// at least 0. `None` when the line does not cross `c` at two points or nothing is left. +fn clip_to_side(outline: &PathData, c: &[Point], values: &[f64], sign: f64) -> Option { + let mut crossings = vec![]; + for (j, (&a, &va)) in c.iter().zip(values).enumerate() { + let k = (j + 1) % c.len(); + let (Some(&b), Some(&vb)) = (c.get(k), values.get(k)) else { continue }; + if (va >= 0.0) != (vb >= 0.0) { + crossings.push(a.lerp(b, va / (va - vb))); + } + } + let &[q0, q1] = crossings.as_slice() else { return None }; + let along = q1 - q0; + let length = along.hypot(); + if length.is_nan() || length <= 1e-9 { + return None; + } + let along = along / length; + let (inside, _) = c.iter().zip(values).find(|(_, v)| **v * sign > 0.0)?; + let mut across = Vec2::new(-along.y, along.x); + if (*inside - q0).dot(across) < 0.0 { + across = -across; + } + let bounds = outline.bounds()?.union(polygon_bounds(c)); + let reach = 2.0 * (bounds.width() + bounds.height() + (q0 - bounds.center()).hypot()) + 1.0; + let mut side = BezPath::new(); + side.move_to(q0 - along * reach); + side.line_to(q0 + along * reach); + side.line_to(q0 + along * reach + across * reach); + side.line_to(q0 - along * reach + across * reach); + side.close_path(); + let kept = vectorcraft_pathops::boolean(outline, FillRule::NonZero, &PathData::from_bezpath(&side), FillRule::NonZero, BoolOp::Intersect); + kept.bounds().is_some().then_some(kept) +} + +/// The part of polygon `p` where `sign` times `values` (one per point, varying linearly along each +/// edge) is at least 0. +fn half(p: &[Point], values: &[f64], sign: f64) -> Vec { + let mut out = vec![]; + for (j, (&a, &va)) in p.iter().zip(values).enumerate() { + let k = (j + 1) % p.len(); + let (Some(&b), Some(&vb)) = (p.get(k), values.get(k)) else { continue }; + let (sa, sb) = (va * sign, vb * sign); + if sa >= 0.0 { + out.push(a); + } + if (sa >= 0.0) != (sb >= 0.0) { + out.push(a.lerp(b, sa / (sa - sb))); + } + } + out +} + +/// `order` (back to front), when it draws a face of one of a shape's strokes and an overlapping face +/// of the same shape's fill or strokes the wrong way round for their depths where they overlap on +/// the drawing, with every pair of overlapping faces that keep a polygon and a plane +/// ([`convex_face`]: turned toward the viewer, not a planar end), of any shape, put in the order of +/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill +/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each +/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays +/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`. +/// Otherwise `order` as it is. +fn local_order(faces: &[Placed], order: Vec) -> Vec { + use std::cmp::Reverse; + // The faces of each shape that take part, from left to right for a sweep along x. + let mut shapes: Vec> = vec![]; + for (k, f) in faces.iter().enumerate() { + if f.outline.len() < 3 || f.plane.is_none() { + continue; + } + if shapes.len() <= f.member { + shapes.resize_with(f.member + 1, Vec::new); + } + shapes[f.member].push(k); + } + if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) { + return order; + } + for list in &mut shapes { + list.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); + } + // A fill wall and a face of the same shape's covering stroke keep the order [`draw_order`] gave + // them: the stroke's solid holds the wall, which never shows. + let covered = |f: &Placed, s: &Placed| f.paints == Paints::Fill && f.side && s.paints == Paints::Stroke && f.member == s.member; + // Is there a face of a shape's strokes and a face of the same shape's fill or strokes that the + // order of their depths draws the wrong way round where they overlap? + let mut position = vec![0usize; faces.len()]; + for (at, &k) in order.iter().enumerate() { + position[k] = at; + } + let mut checks = 0usize; + let mut misordered = false; + 'shapes: for list in &shapes { + for (i, &f) in list.iter().enumerate() { + let a = &faces[f]; + for &s in list.iter().skip(i + 1).take_while(|&&s| faces[s].bounds.x0 < a.bounds.x1) { + if checks >= MAX_LOCAL_CHECKS { + break 'shapes; + } + checks += 1; + let b = &faces[s]; + if (a.paints == Paints::Fill && b.paints == Paints::Fill) || covered(a, b) || covered(b, a) || !rects_overlap(a.bounds, b.bounds) { + continue; + } + if nearer_where_overlapping(a, b).is_some_and(|a_nearer| a_nearer != (position[f] > position[s])) { + misordered = true; + break 'shapes; + } + } + } + } + if !misordered { + return order; + } + // Moving those faces must not carry them past any other face they overlap, so every pair of + // faces with a polygon and a plane that overlap goes in the order of their depths there. + let mut sweep: Vec = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect(); + sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); + // For each face, the faces drawn after it, and for each, how many go before it. + let mut after: Vec> = vec![vec![]; faces.len()]; + let mut waits = vec![0usize; faces.len()]; + 'pairs: for (i, &k) in sweep.iter().enumerate() { + let a = &faces[k]; + for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) { + if checks >= MAX_LOCAL_CHECKS { + break 'pairs; + } + checks += 1; + let b = &faces[j]; + if !rects_overlap(a.bounds, b.bounds) { + continue; + } + let a_later = if covered(a, b) || covered(b, a) { + position[k] > position[j] + } else { + let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue }; + a_nearer + }; + let (back, front) = if a_later { (j, k) } else { (k, j) }; + after[back].push(front); + waits[front] += 1; + } + } + // Each step draws the face that comes first in `order` of those whose faces before are drawn. + let mut ready: std::collections::BinaryHeap> = + (0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); + let mut drawn = vec![false; faces.len()]; + let mut out = Vec::with_capacity(order.len()); + let mut first = 0usize; + while out.len() < order.len() { + let k = match ready.pop() { + Some(Reverse((_, k))) => k, + None => { + // A cycle: the first face in `order` not drawn yet goes next. + while order.get(first).is_some_and(|&k| drawn[k]) { + first += 1; + } + let Some(&k) = order.get(first) else { break }; + k + } + }; + if drawn[k] { + continue; + } + drawn[k] = true; + out.push(k); + for &j in &after[k] { + waits[j] = waits[j].saturating_sub(1); + if waits[j] == 0 && !drawn[j] { + ready.push(Reverse((position[j], j))); + } + } + } + out +} + +/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing, +/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is +/// not convex, or when they are at the same depth there. +fn nearer_where_overlapping(a: &Placed, b: &Placed) -> Option { + let (pa, pb) = (a.plane?, b.plane?); + let turn = convex(&b.outline)?; + convex(&a.outline)?; + let overlap = clip_convex(&a.outline, &b.outline, turn); + let mid = centroid(&overlap)?; + let (da, db) = (pa.depth_at(mid)?, pb.depth_at(mid)?); + let tolerance = 1e-6 * (1.0 + da.abs().max(db.abs())); + ((da - db).abs() > tolerance).then_some(da > db) +} + +/// The sign of the turns of convex polygon `p` (`None` when it is not convex or has no area). +fn convex(p: &[Point]) -> Option { + let n = p.len(); + let mut sign = 0.0; + for i in 0..n { + let (a, b, c) = (p[i], p[(i + 1) % n], p[(i + 2) % n]); + let cross = (b - a).cross(c - b); + if cross.abs() <= 1e-12 { + continue; + } + if sign == 0.0 { + sign = cross.signum(); + } else if cross.signum() != sign { + return None; + } + } + (sign != 0.0).then_some(sign) +} + +/// The part of polygon `subject` inside convex polygon `clip`, whose turns have sign `turn` +/// (Sutherland–Hodgman). +fn clip_convex(subject: &[Point], clip: &[Point], turn: f64) -> Vec { + let mut out = subject.to_vec(); + for i in 0..clip.len() { + if out.is_empty() { + break; + } + let (e0, e1) = (clip[i], clip[(i + 1) % clip.len()]); + let side = |p: Point| (e1 - e0).cross(p - e0) * turn; + let input = std::mem::take(&mut out); + for j in 0..input.len() { + let (p, q) = (input[j], input[(j + 1) % input.len()]); + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + let t = sp / (sp - sq); + out.push(p.lerp(q, t)); + } + } + } + out +} + +/// The centroid of polygon `p`, `None` when it has (almost) no area. It is measured from the +/// polygon's first point, so a small polygon far from the origin keeps its area. +fn centroid(p: &[Point]) -> Option { + let origin = *p.first()?; + let n = p.len(); + let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0); + for i in 0..n { + let (a, b) = (p[i] - origin, p[(i + 1) % n] - origin); + let cross = a.x * b.y - b.x * a.y; + area += cross; + cx += (a.x + b.x) * cross; + cy += (a.y + b.y) * cross; + } + (area.abs() > 1e-9).then(|| origin + Vec2::new(cx / (3.0 * area), cy / (3.0 * area))) +} + /// The most bounds comparisons [`draw_order`] makes; the fill walls it has not reached by then keep /// their depths. const MAX_OVERLAP_CHECKS: usize = 4_000_000; @@ -742,7 +1179,8 @@ const MAX_OVERLAP_CHECKS: usize = 4_000_000; /// of a shape's fill turned toward the viewer is drawn before each face of the same shape's /// covering strokes ([`Paints::Stroke`]), turned toward the viewer, whose bounds overlap its own. /// Such a stroke's closed solid holds the fill's walls, so they never show and can be drawn under -/// any other face. +/// any other face. A shape's fill faces and the faces of its other strokes then go in the order of +/// their depths where they overlap ([`local_order`]). fn draw_order(faces: &[Placed], sealed: bool) -> Vec { // Each face's depth to sort by, and whether it was moved before a stroke face at that depth. let mut keys: Vec<(f64, bool)> = faces.iter().map(|f| (f.depth, false)).collect(); @@ -781,7 +1219,7 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec { // A stable sort: faces at the same depth keep the order of the appearance, and a fill's side // face moved to a stroke face's depth goes before it. order.sort_by(|&a, &b| keys[a].0.total_cmp(&keys[b].0).then(keys[b].1.cmp(&keys[a].1))); - order + local_order(faces, order) } /// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before` @@ -806,7 +1244,9 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// each in its own paint. When every one is opaque with normal blending and no colored light makes /// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as /// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's -/// fill walls before the faces of its covering strokes that overlap them: [`draw_order`]), the +/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and +/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the +/// order of their depths where they overlap: [`draw_order`]), the /// faces of a solid in a gradient with transparent stops in runs that carry its opacity mask /// ([`in_runs`]); /// otherwise each solid is a surface of its own, in that order. A member's opacity mask and @@ -995,18 +1435,22 @@ type BuiltSurface<'s> = (Vec, Node, &'s [Scope], Vec> /// [`with_graphics`] of built surfaces, each drawn whole. fn whole_surfaces<'s>(surfaces: Vec>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { - with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts) + with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts) } -/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each -/// right after its surface, with that surface's scopes and its opacity mask (a gradient's -/// transparency), so a graphic is hidden where its cap is. -fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc)>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { +/// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts` +/// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes +/// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is. +fn with_graphics<'s>( + surfaces: Vec<(&'s [Scope], Arc)>, + first: usize, + arts: &[(usize, PlanarFace, Arc)], +) -> Vec<(&'s [Scope], Arc)> { let mut out = Vec::with_capacity(surfaces.len() + arts.len()); for (k, (scopes, s)) in surfaces.into_iter().enumerate() { let mask = s.extras().mask.clone(); out.push((scopes, s)); - out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| { + out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| { let mut art = art.clone(); if let Some(mask) = &mask { Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone()); @@ -1058,7 +1502,7 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile } } let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks); - let out = with_graphics(out, &arts); + let out = with_graphics(out, 0, &arts); return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); } let (parts, bounds) = solid_parts(shapes, b); @@ -1085,6 +1529,43 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let (_, opacity, blend) = paint_of(item, *member); opacity >= 1.0 && blend == BlendMode::Normal }); + let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path)); + // A solid whose surface is one composite of all its facets ([`surface`]: a solid color under + // colored lights with smooth shading) has no faces to order. + let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some()); + // The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under + // a member's opacity mask or blending, each member's faces go in one order of their own when its + // fills and strokes are opaque, blend normally, carry no opacity mask and are not composites. + let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f)); + let shape_order: Vec = (0..shapes.len()) + .map(|shape| { + solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| { + let (paint, opacity, blend) = paint_of(item, *member); + opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f) + }) + }) + .collect(); + let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order }; + if solids.iter().any(|s| ordered(s.4)) { + // A stroke face that passes through a fill wall or another stroke's face is cut where it + // does. The pieces count against the limits as the faces did: cutting stops before the + // faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that + // draws uncut still draws. + let counts: Vec = solids.iter().map(|(.., f, _)| f.len()).collect(); + let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes); + let mut cuts: Vec<(Paints, usize, &mut Vec)> = solids + .iter_mut() + .filter(|(.., shape)| ordered(*shape)) + .map(|(item, _, _, f, shape)| (Paints::of(item, closed(*shape)), *shape, f)) + .collect(); + cut_stroke_faces(&mut cuts, room); + for ((item, _, _, f, _), before) in solids.iter().zip(counts) { + let added = f.get(before..).unwrap_or_default(); + if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(added, paint_ref(item), colored), paint_ref(item)) { + return None; + } + } + } let arts = if !graphics_on { vec![] } else { @@ -1100,11 +1581,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile .collect(); placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks) }; + let members: Vec = solids.iter().map(|s| s.4).collect(); let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { - let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed)); - let paints = Paints::of(item, closed); + let paints = Paints::of(item, closed(shape)); let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); @@ -1112,50 +1593,86 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile (depths, art, scopes, ends) }) .collect(); - if masks { - return Some(masked(n.id, whole_surfaces(surfaces, &arts))); - } - // One order takes a plain group of faces from each solid, one face for each facet. With - // colored lights a surface can instead be one clipped composite of all its facets. A composite - // has no faces to order, so when any surface is one, every surface of the solid, masked ones - // included, draws whole in member order. - let plain = - surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())); - // A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs - // ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole, - // each graphic right after its surface. - let masks: Vec>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); - let masked_faces = masks.iter().any(Option::is_some); - if !opaque || !plain || (masked_faces && !arts.is_empty()) { - return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); - } - let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); - for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { - if let NodeKind::Group { children, .. } = s.kind { - placed.extend(depths); - faces.extend(children.into_iter().map(|face| Some((surface, face)))); - ends.extend(e); - } - } let sealed = match fx.id.as_str() { INFLATE => inflate_options(&p).cap, CLASSIC_EXTRUDE => classic_extrude_options(&p).cap, _ => extrude_options(&p).cap, }; + // One order takes a plain group of faces from each solid, one face for each facet. With + // colored lights a surface can instead be one clipped composite of all its facets. A composite + // has no faces to order, so it draws whole. + let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()); + if masks { + // Each member's surfaces, in the scopes of its opacity mask or blending: its faces in one + // order when it is opaque and plain, otherwise each surface whole. + let mut out = vec![]; + let mut surfaces = surfaces.into_iter().zip(members).enumerate().peekable(); + while let Some((first, (s, member))) = surfaces.next() { + let mut run = vec![s]; + while let Some((_, (s, _))) = surfaces.next_if(|(_, (_, m))| *m == member) { + run.push(s); + } + let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none()); + if ordered(member) && flat { + let scopes = run.first().map_or(&[][..], |s| s.2); + out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed))))); + } else { + out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts)); + } + } + return Some(masked(n.id, out)); + } + if !opaque || !surfaces.iter().all(plain) { + return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); + } + Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))]) +} + +/// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in +/// one order ([`draw_order`], `sealed` for solids with caps), each of the graphics `arts` of those +/// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops +/// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of +/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is. +fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: &[(usize, PlanarFace, Arc)], sealed: bool) -> Vec> { + let masks: Vec>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); + let arts: Vec<&(usize, PlanarFace, Arc)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect(); + let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); + for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { + if let NodeKind::Group { children, .. } = s.kind { + placed.extend(depths); + faces.extend(children.into_iter().map(|face| Some((surface, face)))); + ends.extend(e.into_iter().map(|end| end.map(|end| (surface, end)))); + } + } let order = draw_order(&placed, sealed); - if masked_faces { - let faces: Vec<(usize, Arc)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect(); - return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]); - } - // Each face's graphics go right after the last of the faces they are drawn on. - let last: Vec> = - arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect(); - let mut children = Vec::with_capacity(order.len() + arts.len()); + // Each graphic goes right after the last of the faces it is drawn on, among the surfaces that + // share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a + // mask that ends at its surface. + let last: Vec> = arts + .iter() + .map(|(at, face, _)| { + let at = at - first; + let from = if masks.get(at).is_some_and(Option::is_some) { + at + } else { + masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1) + }; + order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface))) + }) + .collect(); + let mut drawn: Vec<(usize, Arc)> = Vec::with_capacity(order.len() + arts.len()); for (at, k) in order.into_iter().enumerate() { - children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face)); - children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone())); + drawn.extend(faces.get_mut(k).and_then(Option::take)); + drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| { + let mut art = art.clone(); + if let Some(mask) = masks.get(surface - first).cloned().flatten() { + Arc::make_mut(&mut art).extras_mut().mask = Some(mask); + } + // An index past the surfaces: the graphic goes in a run of its own, with its own mask. + (masks.len(), art) + })); } - Some(vec![Arc::new(Node::group(n.id, children))]) + if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() } } /// `faces` in their back-to-front order, each with the index of its surface, where some surfaces diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index b4e012f977..3c2795dd1b 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -253,6 +253,437 @@ fn a_fills_walls_are_drawn_before_the_stroke_faces_over_them() { } } +/// The faces of the solids effect `id` with `params` builds for `n`, in the order they are drawn, +/// as [`surfaces_for`] orders them, each with the index of the part ([`solid_parts`]) it was built +/// from and whether it is a stroke's. +fn drawn_parts(n: &Node, id: &str, params: &Value) -> Vec<(Facet, usize, bool)> { + let (path, rule) = profile(n).unwrap(); + let shapes = [Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]; + let p = crate::merged_params(id, params); + let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); + let mut solids = vec![]; + for (part, ((item, _, _, _, _, member), f)) in parts.iter().zip(built_solids(id, &p, &parts, bounds, MAX_OBJECT_FACES)).enumerate() { + let Some(f) = f.unwrap() else { continue }; + let closed = holds_edge(id, &shapes[*member].path); + solids.push((Paints::of(item, closed), *member, f, part, matches!(item, AppearanceItem::Stroke(_)))); + } + let mut cuts: Vec<(Paints, usize, &mut Vec)> = solids.iter_mut().map(|(paints, member, f, _, _)| (*paints, *member, f)).collect(); + cut_stroke_faces(&mut cuts, MAX_OBJECT_FACES); + let (mut placed, mut all) = (vec![], vec![]); + for (paints, member, f, part, stroke) in solids { + for facet in f { + placed.push(Placed::of(&facet, member, paints)); + all.push((facet, part, stroke)); + } + } + let sealed = match id { + INFLATE => inflate_options(&p).cap, + CLASSIC_EXTRUDE => classic_extrude_options(&p).cap, + _ => extrude_options(&p).cap, + }; + draw_order(&placed, sealed).into_iter().map(|k| all[k].clone()).collect() +} + +/// Is `p` inside the polygon of `f` (nonzero winding)? +fn facet_contains(f: &Facet, p: Point) -> bool { + let mut winding = 0i32; + for c in &f.contours { + for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) { + let cross = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y); + if a.y <= p.y && b.y > p.y && cross > 0.0 { + winding += 1; + } else if a.y > p.y && b.y <= p.y && cross < 0.0 { + winding -= 1; + } + } + } + winding != 0 +} + +/// The points of a 1 pt grid over `faces` (drawn in that order, each with whether it is a stroke's) +/// where the face drawn on top is the fill's while a face of the stroke turned toward the viewer is +/// nearer the viewer there by more than 0.5 pt, or the other way round. Points within 0.3 pt of an +/// edge are left out. +fn wrong_on_top(faces: &[(Facet, bool)]) -> Vec { + let polygons: Vec<&Facet> = faces.iter().map(|(f, _)| f).collect(); + let extent = + polygons.iter().flat_map(|f| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p)); + let mut wrong = vec![]; + let mut y = extent.y0.floor() + 0.5; + while y < extent.y1 { + let mut x = extent.x0.floor() + 0.5; + while x < extent.x1 { + let p = Point::new(x, y); + let well_inside = |f: &Facet| { + [(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy))) + }; + let top = faces.iter().rposition(|(f, _)| facet_contains(f, p)); + if let Some((f, stroke)) = top.and_then(|k| faces.get(k)).filter(|(f, _)| !f.away && well_inside(f)) { + let nearest = |of_stroke: bool| { + faces.iter().filter(|(g, s)| *s == of_stroke && !g.away && well_inside(g)).filter_map(|(g, _)| g.depth_at(p)).reduce(f64::max) + }; + if let (Some(ds), Some(df)) = (nearest(true), nearest(false)) + && (ds - df).abs() > 0.5 + && (ds > df) != *stroke + && f.depth_at(p).is_some() + { + wrong.push(p); + } + } + x += 1.0; + } + y += 1.0; + } + wrong +} + +/// The points of a 1 pt grid over `faces` (drawn in that order) where the face drawn on top is +/// farther from the viewer than another face turned toward the viewer, of any part, by more than +/// 0.5 pt. Points within 0.3 pt of an edge, and faces without a plane, are left out. +fn misdrawn(faces: &[(Facet, usize, bool)]) -> Vec { + let extent = + faces.iter().flat_map(|(f, ..)| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p)); + let mut wrong = vec![]; + let mut y = extent.y0.floor() + 0.5; + while y < extent.y1 { + let mut x = extent.x0.floor() + 0.5; + while x < extent.x1 { + let p = Point::new(x, y); + let well_inside = |f: &Facet| { + [(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy))) + }; + let top = faces.iter().rposition(|(f, ..)| facet_contains(f, p)).and_then(|k| faces.get(k)).filter(|(f, ..)| !f.away && well_inside(f)); + if let Some(on_top) = top.and_then(|(f, ..)| f.depth_at(p)) { + let nearest = faces.iter().filter(|(g, ..)| !g.away && well_inside(g)).filter_map(|(g, ..)| g.depth_at(p)).reduce(f64::max); + if nearest.is_some_and(|d| d - on_top > 0.5) { + wrong.push(p); + } + } + x += 1.0; + } + y += 1.0; + } + wrong +} + +/// The faces of a shape's fill and strokes are drawn in the order of their depths where they +/// overlap: on a turned C, with or without perspective, under a stroke that does not cover the +/// fill's whole edge (dashed, with a width profile, or with a brush), under a plain stroke and +/// under two strokes whose faces pass through each other, no point shows a face farther from the +/// viewer than another, in Extrude & Bevel and Extrude & Bevel (Classic), and only a few in +/// Inflate, where curved puffs cross. +#[test] +fn fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap() { + use vectorcraft_doc::{Dash, WidthProfile}; + let views = [ + json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}), + json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10}), + json!({"rotationX": -30, "rotationY": 50, "rotationZ": 5, "perspectiveAngle": 40}), + json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}), + ]; + type Style<'a> = (&'a str, &'a dyn Fn(&mut Node)); + let first = |n: &mut Node, set: &dyn Fn(&mut StrokeLayer)| { + if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + set(s); + } + }; + let dash = |pattern: Vec, offset: f64| Some(Dash { pattern, offset, align_corners: false }); + let styles: [Style; 6] = [ + ("plain", &|_| {}), + ("dashed", &|n| first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0))), + ("profiled", &|n| first(n, &|s| s.profile = Some(WidthProfile::lens()))), + ("brushed", &|n| first(n, &|s| s.brush = Some("brush".into()))), + ("dashed with perspective", &|n| first(n, &|s| s.dash = dash(vec![20.0, 6.0], 3.0))), + ("two strokes", &|n| { + first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0)); + let mut wide = StrokeLayer::new(Paint::solid(RED), 14.0); + wide.profile = Some(WidthProfile::lens()); + n.appearance.items.push(AppearanceItem::Stroke(wide)); + }), + ]; + for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] { + for (v, view) in views.iter().enumerate() { + for (style, set) in &styles { + // The last two views, for the plain and the two strokes only. + if v >= 2 && !["plain", "two strokes"].contains(style) { + continue; + } + let mut params = view.clone(); + params["depth"] = json!(60); + if style.contains("perspective") { + params["perspectiveAngle"] = json!(40); + } + let mut n = stroked(&letter_c()); + set(&mut n); + let parts = drawn_parts(&n, id, ¶ms); + let faces: Vec<(Facet, bool)> = parts.iter().map(|(f, _, s)| (f.clone(), *s)).collect(); + assert!(faces.iter().any(|(_, s)| *s) && faces.iter().any(|(_, s)| !*s), "{id} {view} {style}: faces of both"); + // Inflate's curved puffs cross each other along curves its flat facets only follow + // roughly: a few points next to those crossings may still show the farther face. + let allowed = if id == INFLATE { 5 } else { 0 }; + let wrong = wrong_on_top(&faces); + assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points drawn in the wrong paint, first {:?}", wrong.len(), wrong.first()); + let wrong = misdrawn(&parts); + assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points show a farther face, first {:?}", wrong.len(), wrong.first()); + } + } + } +} + +/// The paths of `art`'s faces in drawing order, leaving out the graphics (clip groups). +fn face_paths(art: &Node) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Group { clip: true, .. } => {} + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ => out.extend(n.path_data().cloned()), + } + } + let mut out = vec![]; + walk(art, &mut out); + out +} + +/// A member of a 3D group with an opacity mask or a blending mode of its own draws its fill's and +/// its strokes' faces in one order inside that mask, the order the same member draws them in +/// without it, its dashes cut where they pass through the fill's walls. A member whose stroke is +/// translucent still draws each surface whole. +#[test] +fn a_masked_members_fill_and_stroke_faces_go_in_one_order() { + let mut member = stroked(&letter_c()); + if let Some(AppearanceItem::Stroke(s)) = member.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + } + let solid = |member: Node| { + let mut g = Node::group(NodeId(2), vec![Arc::new(member)]); + g.appearance.effects.push(fx(EXTRUDE, json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60}))); + solid_art(&g).unwrap() + }; + let cover = Node::path( + NodeId(900), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let mut masked = member.clone(); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true))); + let mut multiplied = member.clone(); + multiplied.blend = BlendMode::Multiply; + let unmasked = face_paths(&solid(member.clone())); + for (what, scoped) in [("masked", masked.clone()), ("multiplied", multiplied)] { + let art = solid(scoped); + let mut scopes = 0; + art.walk(&mut |n| scopes += usize::from(n.extras().mask.is_some() || n.blend == BlendMode::Multiply)); + assert!(scopes > 0, "{what}: drawn in its scope"); + assert_eq!(face_paths(&art), unmasked, "{what}: the faces in the member's one order"); + } + // A translucent stroke keeps its surface whole: the fill's faces, then the stroke's. + if let Some(AppearanceItem::Stroke(s)) = masked.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.opacity = 0.5; + } + let art = solid(masked); + let mut groups = vec![]; + art.walk(&mut |n| { + if n.opacity == 0.5 { + groups.push(n.children().map_or(0, Vec::len)); + } + }); + assert_eq!(groups.len(), 1, "the stroke's surface is one translucent group"); +} + +/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the +/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color, +/// drawn as one composite of each surface's facets, still draws each surface whole. +#[test] +fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let gradient = |c: Color| { + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)], + )))) + }; + let mut n = stroked(&letter_c()); + for item in &mut n.appearance.items { + match item { + AppearanceItem::Fill(f) => f.paint = gradient(RED), + AppearanceItem::Stroke(s) => { + s.paint = gradient(BLUE); + s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + } + } + } + // How many surfaces the art draws, and how many faces the first holds. + let drawn = |n: &Node, lights: Option| { + let mut n = n.clone(); + let mut p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60}); + if let Some(lights) = lights { + p["lights"] = lights; + } + n.appearance.effects.push(fx(INFLATE, p)); + let art = solid_art(&n).unwrap(); + let surfaces = art.children().unwrap(); + (surfaces.len(), surfaces[0].children().map_or(0, Vec::len)) + }; + let colored = json!([{"color": "#ff8080"}]); + let white = drawn(&n, None); + assert_eq!(white.0, 1, "one order"); + let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len(); + assert_eq!(white.1, cut, "the white light's faces, cut"); + assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light"); + // A solid color under the colored light: a composite for each of the fill and the stroke. + let solid = stroked(&letter_c()); + assert_eq!(drawn(&solid, Some(colored)).0, 2); +} + +/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they +/// overlap is cut along the line where their depths meet, into the piece in front of the wall and +/// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke +/// and a cut past the room left are left whole. +#[test] +fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { + let facet = |x: f64, normal: [f64; 3], offset: f64| Facet { + contours: vec![vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal, + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); + // z = x - 8: behind the wall left of x = 8, in front of it right of it. + let r = std::f64::consts::FRAC_1_SQRT_2; + let mut through = facet(5.0, [-r, 0.0, r], -8.0 * r); + // Its curved outline: the top edge bows up to y = -2. + let mut curved = BezPath::new(); + curved.move_to((5.0, 0.0)); + curved.curve_to((8.0, -8.0 / 3.0), (12.0, -8.0 / 3.0), (15.0, 0.0)); + curved.line_to((15.0, 10.0)); + curved.line_to((5.0, 10.0)); + curved.close_path(); + through.outline = Some(PathData::from_bezpath(&curved)); + let extent = |f: &Facet| polygon_bounds(&f.contours[0]); + let cut_with = |paints: Paints, member: usize, room: usize| { + let (mut fill, mut stroke) = (vec![wall.clone()], vec![through.clone()]); + let mut solids: Vec<(Paints, usize, &mut Vec)> = vec![(Paints::Fill, 0, &mut fill), (paints, member, &mut stroke)]; + cut_stroke_faces(&mut solids, room); + stroke + }; + let pieces = cut_with(Paints::Other, 0, 10); + assert_eq!(pieces.len(), 2); + let (near, far) = (extent(&pieces[0]), extent(&pieces[1])); + assert!((near.x0 - 8.0).abs() < 1e-9 && near.x1 == 15.0 && far.x0 == 5.0 && (far.x1 - 8.0).abs() < 1e-9, "{near:?} {far:?}"); + assert!(pieces[0].depth > 0.0 && pieces[1].depth < 0.0); + // Each piece keeps its side of the curved outline, the bowed edge included. + let curve = |f: &Facet| f.outline.as_ref().and_then(PathData::bounds).unwrap(); + let (near, far) = (curve(&pieces[0]), curve(&pieces[1])); + assert!((near.x0 - 8.0).abs() < 1e-6 && (near.x1 - 15.0).abs() < 1e-6 && near.y0 < -1.5, "{near:?}"); + assert!((far.x0 - 5.0).abs() < 1e-6 && (far.x1 - 8.0).abs() < 1e-6 && far.y0 < -1.5, "{far:?}"); + let whole = std::slice::from_ref(&through); + assert_eq!(cut_with(Paints::Other, 1, 10), whole, "another shape's stroke"); + assert_eq!(cut_with(Paints::Stroke, 0, 10), whole, "a covering stroke"); + assert_eq!(cut_with(Paints::Other, 0, 0), whole, "no room"); + let (mut fill, mut stroke) = (vec![wall.clone()], vec![facet(5.0, [0.0, 0.0, 1.0], 1.0)]); + cut_stroke_faces(&mut [(Paints::Fill, 0, &mut fill), (Paints::Other, 0, &mut stroke)], 10); + assert_eq!(stroke.len(), 1, "in front of the wall wherever they overlap"); + // Of two of a shape's strokes whose faces pass through each other, the later stroke's face is + // cut against the earlier one's; a covering stroke's face is never cut, and the other stroke's + // face is cut against it. Two shapes' strokes are left whole. + for (case, (first, second, cut_first)) in + [(Paints::Other, Paints::Other, false), (Paints::Stroke, Paints::Other, false), (Paints::Other, Paints::Stroke, true)].into_iter().enumerate() + { + let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]); + cut_stroke_faces(&mut [(first, 0, &mut a), (second, 0, &mut b)], 10); + assert_eq!((a.len(), b.len()), if cut_first { (2, 1) } else { (1, 2) }, "case {case}"); + } + let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]); + cut_stroke_faces(&mut [(Paints::Other, 0, &mut a), (Paints::Other, 1, &mut b)], 10); + assert_eq!((a.len(), b.len()), (1, 1), "two shapes"); +} + +/// A small polygon far from the origin keeps its area and centroid. +#[test] +fn a_small_polygon_far_away_has_a_centroid() { + let far = 100_000_000.0; + let square = [Point::new(far, far), Point::new(far + 1.0, far), Point::new(far + 1.0, far + 1.0), Point::new(far, far + 1.0)]; + let c = centroid(&square).unwrap(); + assert!((c.x - far - 0.5).abs() < 1e-6 && (c.y - far - 0.5).abs() < 1e-6, "{c:?}"); + assert!(centroid(&[]).is_none() && centroid(&square[..2]).is_none()); +} + +/// Cutting adds no more faces than the object's face limit and the paint-copy allowance leave room +/// for, so an effect that draws with its faces uncut still draws. +#[test] +fn cutting_stays_within_the_face_limit_and_the_paint_allowance() { + let items = stroked(&letter_c()).appearance.items.clone(); + let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap(); + let mut one = 0usize; + crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke)); + let max = crate::revolve::MAX_PAINT_COPIES; + assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one)); + assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0); + assert_eq!(cut_room(items.iter(), 10, max - 3 * one), 3); + assert_eq!(cut_room(items.iter(), 10, max + 1), 0); +} + +/// Where a shape's fill wall and a face of its stroke that leaves gaps overlap, the one nearer the +/// viewer there is drawn after the other, whichever their depths put first; a stroke face that +/// overlaps no fill wall keeps its place. +#[test] +fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let at = |depth: f64, x: f64, z: f64, paints: Paints| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints, + outline: square(x), + plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: z, center: Point::ZERO, eye: None }), + }; + // 0 a fill wall at z 0; 1 a stroke face over half of it, nearer, sorted before it; 2 a stroke + // face elsewhere; 3 a stroke face over it, farther, sorted after it. + let faces = + [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 1.0, Paints::Other), at(1.0, 20.0, 1.0, Paints::Other), at(6.0, 2.0, -1.0, Paints::Other)]; + assert_eq!(draw_order(&faces, true), [2, 3, 0, 1]); + assert_eq!(draw_order(&faces, false), [2, 3, 0, 1]); + // A covering stroke's faces keep the wall's own rule. + let covering: Vec = faces + .iter() + .map(|f| Placed { paints: if f.paints == Paints::Other { Paints::Stroke } else { f.paints }, outline: vec![], plane: None, ..*f }) + .collect(); + assert_eq!(draw_order(&covering, false), [2, 1, 0, 3]); + // Another shape's stroke, and a stroke face at the same depth where they overlap, move nothing. + let other_shape: Vec = + faces[..3].iter().map(|f| Placed { member: usize::from(f.paints == Paints::Other), outline: f.outline.clone(), ..*f }).collect(); + assert_eq!(draw_order(&other_shape, true), [2, 1, 0]); + let level = [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 0.0, Paints::Other)]; + assert_eq!(draw_order(&level, true), [1, 0]); + // A stroke face moved after its fill's wall does not pass a nearer face of another shape that + // it overlaps: 0 a stroke face, 1 another shape's face in front of both, 2 the fill's wall. + let in_front = Placed { member: 1, ..at(2.0, 5.0, 2.0, Paints::Fill) }; + let shapes = [at(1.0, 5.0, 1.0, Paints::Other), in_front, at(3.0, 0.0, 0.0, Paints::Fill)]; + assert_eq!(draw_order(&shapes, true), [2, 0, 1]); + // A shape with a covering stroke as well keeps its fill wall before the covering stroke's face, + // even where that face is the farther: 0 the fill's wall, 1 the covering stroke's face behind + // it, 2 the other stroke's face in front. + let both = [at(3.0, 0.0, 0.0, Paints::Fill), at(3.0, 0.0, -1.0, Paints::Stroke), at(2.0, 5.0, 1.0, Paints::Other)]; + assert_eq!(draw_order(&both, true), [0, 1, 2]); + // Faces of a shape's strokes go in the order of their depths where they overlap too, with no + // fill face among them: 1 is nearer than 0 there, though sorted before it. + for (case, (back, front)) in + [(Paints::Other, Paints::Other), (Paints::Stroke, Paints::Other), (Paints::Stroke, Paints::Stroke)].into_iter().enumerate() + { + let strokes = [at(5.0, 0.0, 0.0, back), at(2.0, 5.0, 1.0, front)]; + assert_eq!(draw_order(&strokes, true), [0, 1], "case {case}"); + } +} + /// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a /// face of the same shape's stroke drawn before it: the wall then goes just before that face. A /// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an @@ -266,6 +697,8 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() { bounds: Rect::new(x, 0.0, x + 10.0, 10.0), member, paints, + outline: vec![], + plane: None, }; // 0 the fill's wall; 1 the stroke's wall over it; 2 another shape's stroke over it; 3 a stroke // wall elsewhere; 4 a stroke face turned away; 5 a fill cap; 6 the stroke's cap, nearer; 7 a @@ -292,6 +725,9 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() { }; assert!(Paints::of(&stroke(&|_| {}), true) == Paints::Stroke); assert!(Paints::of(&stroke(&|_| {}), false) == Paints::Other, "an open shape"); + let closed = profile(&stroked(&letter_c())).unwrap().0; + assert!(holds_edge(EXTRUDE, &closed) && holds_edge(CLASSIC_EXTRUDE, &closed)); + assert!(!holds_edge(INFLATE, &closed), "an inflated fill can rise in front of its stroke"); assert!(Paints::of(&stroke(&|s| s.width = 0.0), true) == Paints::Other, "no width"); let dash = vectorcraft_doc::Dash { pattern: vec![4.0, 4.0], offset: 0.0, align_corners: false }; assert!(Paints::of(&stroke(&|s| s.dash = Some(dash.clone())), true) == Paints::Other, "dashes"); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index aa73535fc5..bf219353cf 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -620,6 +620,110 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() { assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]); } +/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its +/// clipping path), leaving out the graphics (clip groups of solid-color paths). +fn face_paths(art: &Node) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Group { children, clip: true } => { + let graphic = children.get(1).is_some_and(|inner| match &inner.kind { + NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| { + p.path_data().is_some() + && p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some())) + }), + _ => false, + }); + if !graphic { + out.extend(children.first().and_then(|c| c.path_data()).cloned()); + } + } + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ => out.extend(n.path_data().cloned()), + } + } + let mut out = vec![]; + walk(art, &mut out); + out +} + +/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke +/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without +/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's. +#[test] +fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); + let solid = |graphics: Value| { + let mut n = object( + EXTRUDE, + json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}), + ); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient.clone())); + } + // A gradient stroke: a solid color under the colored light would be one composite. + let blues = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.5))], + ); + let mut stroke = StrokeLayer::new(Paint::Gradient(Box::new(GradientPaint::new(blues))), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + n.appearance.items.push(AppearanceItem::Stroke(stroke)); + solid_art_in(Some(&d), &n).unwrap() + }; + let with = solid(json!([{"symbol": "Mark"}])); + let without = solid(json!([])); + assert!(face_paths(&without).len() > 20, "the faces are found"); + assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order"); + // The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the + // symbol's red square); the fill's, whose surface carries the mask, carries it too. + let mut masked = vec![]; + with.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && let [_, inner] = children.as_slice() + && let NodeKind::Group { children: paths, clip: false } = &inner.kind + && paths.iter().any(|p| { + p.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3), + AppearanceItem::Stroke(_) => false, + }) + }) + { + masked.push(c.extras().mask.is_some()); + } + }); + masked.sort_unstable(); + assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask"); + // The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn + // after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face, + // the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds. + let mut drawn: Vec<(&str, Rect)> = vec![]; + with.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && c.extras().mask.is_some() + && let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds) + { + drawn.push(("graphic", bounds)); + } + let first_stop = c.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => match &f.paint { + Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()), + _ => None, + }, + AppearanceItem::Stroke(_) => None, + }); + if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) { + drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds)); + } + }); + let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap(); + let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0; + assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic"); +} + #[test] fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() { let d = document(); diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 7b778498e6..bab5849c1a 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -9,8 +9,8 @@ mod solid; mod visibility; pub use solid::{ - Bevel, BevelShape, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate, inflate_each, - inflate_together, plane, plane_face_map, + Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate, + inflate_each, inflate_together, plane, plane_face_map, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index f3da6f866f..49b0738d9e 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -292,12 +292,53 @@ pub struct Facet { /// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane /// (its front). `None` for every other facet. pub end: Option, + /// The face's plane in view space and the projection it was drawn with, for its depth at a + /// point of the drawing ([`Facet::depth_at`]). `None` for Revolve's faces and for a face whose + /// corners lie more than 0.001 pt off one plane (a piece of a twisted wall). + pub plane: Option, /// The contours in view space, before projection, for tests that measure depths. #[cfg(test)] view: Vec>, } +/// A facet's plane in view space (x right, y down, z toward the viewer): the points `v` with +/// `normal · v = offset`, drawn by a projection about `center` with the eye `eye` in front of the +/// object's center plane (`None` without perspective). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DepthPlane { + pub normal: [f64; 3], + pub offset: f64, + pub center: Point, + pub eye: Option, +} + +impl DepthPlane { + /// The view-space depth (larger is nearer the viewer) of the point of the plane that projects + /// to `p`, a point of the drawing. `None` when the plane is seen edge-on there or the point is + /// not in front of the eye. + pub fn depth_at(&self, p: Point) -> Option { + let [nx, ny, nz] = self.normal; + let (x, y) = (p.x - self.center.x, p.y - self.center.y); + let z = match self.eye { + None => (nz.abs() > 1e-9).then(|| (self.offset - nx * x - ny * y) / nz)?, + Some(e) => { + // On the ray through `p`, the point at depth z is at (x, y) × (e - z) / e. + let a = (nx * x + ny * y) / e; + let den = nz - a; + let z = (den.abs() > 1e-9).then(|| (self.offset - a * e) / den)?; + (z < e).then_some(z)? + } + }; + z.is_finite().then_some(z) + } +} + impl Facet { + /// The view-space depth of the facet at `p`, a point of the drawing ([`DepthPlane::depth_at`]). + pub fn depth_at(&self, p: Point) -> Option { + self.plane.as_ref()?.depth_at(p) + } + /// About how thick the facet is across: twice its area over its perimeter (a w × l rectangle /// long against its width gives about w). pub fn thickness(&self) -> f64 { @@ -339,6 +380,7 @@ impl Facet { // A revolved cap is not one of the planar faces graphics map onto. end: None, away: false, + plane: None, #[cfg(test)] view: vec![], } diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index bd4030dfc4..1263582df9 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -6,8 +6,8 @@ use super::rings::{ solid_rings_traced, }; use super::{ - Bevel, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, eye_distance, - perspective_scale, + Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, + eye_distance, perspective_scale, }; use crate::shadow::Projection; @@ -129,6 +129,11 @@ impl Builder<'_> { } else { (V3(-n.0, -n.1, -n.2), false) }; + // A face whose corners lie off one plane (a piece of a twisted wall bent into a saddle) has + // no plane to measure its depth on. + let offset = n.dot(centre); + let flat = contours.iter().flatten().all(|v| (n.dot(*v) - offset).abs() <= 1e-3); + let plane = flat.then_some(DepthPlane { normal: [n.0, n.1, n.2], offset, center: self.camera.origin, eye: self.camera.eye }); #[cfg(test)] let view = contours.clone(); let contours: Vec> = contours.iter().map(|c| c.iter().map(|v| self.camera.project(*v)).collect()).collect(); @@ -156,6 +161,7 @@ impl Builder<'_> { side: false, away: behind, end: None, + plane, #[cfg(test)] view, }); diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index be887180b2..b0c26ccc0a 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -154,6 +154,29 @@ fn taper_shrinks_the_back_and_twist_turns_it() { assert!(open.len() > 2 * 8, "{}", open.len()); } +/// A flat facet carries its plane: the depth it gives at each corner of its drawing is the corner's +/// view-space depth, with and without perspective. A piece of a twisted wall whose corners lie off +/// one plane has none. +#[test] +fn a_flat_facet_measures_its_depth_on_its_plane() { + let (p, b) = shape(&square(0.0, 0.0, 100.0)); + let o = Extrude { depth: 60.0, cap: true, ..Extrude::default() }; + for perspective in [0.0, 50.0] { + let view = View { rotation_x: -20.0, rotation_y: 30.0, perspective, ..front() }; + let flat = extrude(&p, FillRule::EvenOdd, b, o, view).unwrap(); + assert!(!flat.is_empty()); + for f in &flat { + assert!(f.plane.is_some(), "{perspective}"); + for (q, v) in f.contours.iter().flatten().zip(f.view.iter().flatten()) { + let d = f.depth_at(*q); + assert!(d.is_some_and(|d| close(d, v.2, 1e-6)), "{perspective}: {d:?} against {}", v.2); + } + } + let twisted = extrude(&p, FillRule::EvenOdd, b, Extrude { twist: 90.0, ..o }, view).unwrap(); + assert!(twisted.iter().any(|f| f.side && f.plane.is_none()), "{perspective}"); + } +} + #[test] fn a_bevel_inside_shrinks_the_cap_and_outside_grows_the_walls() { let (p, b) = shape(&square(0.0, 0.0, 100.0)); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..f447b00c84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1176,6 +1176,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)). - A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`. - With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`. + - When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_cuts_its_dashes_as_a_white_one_does`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`. - Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715). - Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)). - Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`). diff --git a/docs/three-d.md b/docs/three-d.md index c701585b88..e9d5a696ff 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -117,11 +117,20 @@ The rest is our reading: each side face of the fill's solid that is turned toward the viewer is drawn before every face of the same shape's strokes, turned toward the viewer, whose bounds overlap it, so the stroke's walls cover the fill's walls at concave corners. This applies to strokes on closed paths without dashes, a width profile or a brush, painted - with a solid color or a gradient without transparent stops; with other strokes, and without caps, the faces keep - their depth order. Otherwise - each solid is drawn on its own with its opacity and blending, the lower item's first. With a light that is not - white, each solid is also drawn on its own when one of them is a puffed, shaded Inflate surface in a solid color - (drawn as one composite) or is painted with a gradient that has transparent stops (drawn with an opacity mask). + with a solid color or a gradient without transparent stops, under Extrude & Bevel (both kinds). Under Inflate + the fill can rise in front of such a stroke, so it is drawn like the other strokes. Other strokes (dashed, with a + width profile or a brush, on an open subpath, or in a paint that may show through) leave parts of the fill's edge + uncovered, such as the gaps between dashes. Each face of such a stroke that passes through a face of the fill's + solid, or through a face of another of the shape's strokes, where the two overlap in the drawing is cut where + their depths meet, and the faces of the shape's fill and strokes that overlap are drawn in the order of their + depths where they overlap, with caps on or off. A fill wall in a gap stays in its own depth order. Inflate's + curved surfaces follow this only as closely as their flat facets do. A solid painted with a gradient that has + transparent stops under a light that is not white is drawn with an opacity mask: its faces keep their places in + this order, in runs that each carry the mask, and so do its graphics. A member of a 3D group with its own opacity + mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when + they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the + lower item's first. With a light that is not white, each solid is also drawn on its own when one of them is a + puffed, shaded Inflate surface in a solid color (drawn as one composite). - The solids turn, twist and taper about the center of the bounds of all their shapes, Inflate's grid covers those bounds, and with Perspective one eye sees every solid. A stroke too narrow to hold a point of Inflate's grid stays flat. From 08e1b7af8002cefc107673bc970ce833b5f42e0d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:18:53 -0800 Subject: [PATCH 22/28] Image Trace: a background trace applies only to the pixels it traced A trace made away from its command (the background trace, #3098) counted as current when the object, its image record and the settings were unchanged, without looking at the image data. When other pixels came to sit under the same image key (Rasterize after an undo reuses the key and the id, Update Link, a replaced blob), the finished trace applied its old paths to the new image. The trace's inputs now include the encoded bytes it decodes, compared by allocation first and then by content. TraceRun::current and the hand-off in imageTrace.make and imageTrace.makeAndExpand both use them, so a stale trace is dropped and the command traces the pixels there now. Equal bytes in another allocation still count as the same image. --- crates/engine/src/cmd/buildcmds/trace.rs | 30 ++++---- crates/engine/src/tests/build.rs | 97 ++++++++++++++++++++++++ 2 files changed, 114 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 9c6c28b900..11519b84be 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result, + /// The encoded image the tracer decodes: the blob under the image's key, shared with the + /// document. Two blobs are equal when they are the same allocation or hold the same bytes. + bytes: Arc>, } /// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace. @@ -549,7 +553,6 @@ struct Prepared { params_json: Value, preset_label: String, library: Vec<([u8; 3], Paint)>, - bytes: Arc>, } /// What command `c` with params `p` traces, and how, from the session: everything but the trace. @@ -597,8 +600,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { let bytes = Arc::clone(&blob.bytes); let library = trace_library(c, s, &mut params)?; let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; - let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() }; - Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes }) + let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; + Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library }) } /// What a trace made of an image: the size in pixels it was decoded at, and the paths. @@ -616,11 +619,11 @@ impl Traced { } } -/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got -/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`. -fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { +/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has +/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`. +fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { // An image over the tracer's size is traced scaled down (the paths are scaled back). - let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?; + let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?; if !steps(0, 0) { return Err(EngineError::Cancelled); } @@ -682,7 +685,8 @@ impl TraceRun { (self.prepared.inputs.image.width, self.prepared.inputs.image.height) } - /// Does it still apply: would the command trace the same object, image and settings now? + /// Does it still apply: would the command trace the same object, image, pixels and settings + /// now? pub fn current(&self, s: &Session) -> bool { prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs) } @@ -691,13 +695,13 @@ impl TraceRun { /// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no /// document, so it can run on any thread. pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { - trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps) + trace_now(&self.prepared.inputs, &self.prepared.trace, steps) } } pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; - let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?; + let Prepared { inputs, trace, view, params_json, preset_label, library } = prepare(s, c, p)?; let group_by_color = expand && by_color_param(c, p)?; // A saved preset's settings join the journal entry, so a replay traces as this run did after // the preset is changed, renamed or deleted. @@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result traced, - _ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?, + _ => trace_now(&inputs, &trace, &|_, _| true)?, }; let TraceInputs { target, image: img, .. } = inputs; let mut warnings = keep_warnings(&trace, &res); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 49a806b258..21cbf678eb 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3788,6 +3788,103 @@ fn a_trace_run_needs_the_library_colours_it_traced_with() { assert!(!run.current(&s), "{name} changed"); } +/// `image_doc`'s image with its disc 20 px to the left: the same size, other pixels. +fn moved_disc_png() -> Vec { + vectorcraft_trace::Raster::from_fn(100, 100, |x, y| { + let (dx, dy) = (x as f64 + 0.5 - 30.0, y as f64 + 0.5 - 50.0); + if dx * dx + dy * dy <= 900.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] } + }) + .encode_png() +} + +/// Puts `bytes` under the image key `key`, or takes the key's image data away (`None`). +fn set_image_data(s: &mut Session, key: &str, bytes: Option>) { + s.edit("image data", |d, _| { + match bytes { + Some(b) => d.images.insert(key.into(), ImageBlob::new("image/png", b)), + None => d.images.remove(key), + }; + Ok(()) + }) + .unwrap(); +} + +/// The middle of the first traced path of the Image Trace object the reply `r` names, in x. +fn traced_center_x(s: &Session, r: &Value) -> f64 { + outline(&traced_paths(&node(s, NodeId(r["id"].as_u64().unwrap())))[0]).0.bounds().unwrap().center().x +} + +/// A trace made away from its command no longer applies once the pixels under its image's key +/// change, though the object, its image record and the settings stay as they were; both commands +/// then trace the pixels there now. The same bytes in another allocation still apply. +#[test] +fn a_trace_run_needs_the_pixels_it_traced() { + let p = json!({"params": {"ignoreWhite": true}}); + for command in ["imageTrace.make", "imageTrace.makeAndExpand"] { + let mut s = session(); + image_doc(&mut s); + let run = cmd::TraceRun::prepare(&s, command, &p).unwrap(); + let traced = run.run(&|_, _| true).unwrap(); + // The same bytes, allocated anew: still current. + let same = s.doc().unwrap().doc.images["img1"].bytes.to_vec(); + set_image_data(&mut s, "img1", Some(same)); + assert!(run.current(&s), "{command}: equal bytes"); + // Other pixels under the same key: no longer current, and the hand-off is dropped. + set_image_data(&mut s, "img1", Some(moved_disc_png())); + assert!(!run.current(&s), "{command}: other pixels"); + traced.hand_in(&mut s); + let r = s.execute(command, run.params()).unwrap(); + assert!(s.trace_hand_off.is_none(), "{command}: dropped"); + // The disc is now at image x 30, which the ×2 placement at 50 puts at 110. + let x = traced_center_x(&s, &r); + assert!((x - 110.0).abs() < 1.5, "{command}: traced the pixels there now, at {x}"); + } +} + +/// Image data that is missing or empty: a run made before it went no longer applies, the run's +/// command gives the error it gives without a run, and nothing panics. +#[test] +fn a_trace_run_of_missing_or_empty_image_data() { + let p = json!({"params": {"ignoreWhite": true}}); + let mut s = session(); + image_doc(&mut s); + let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap(); + let traced = run.run(&|_, _| true).unwrap(); + set_image_data(&mut s, "img1", None); + assert!(!run.current(&s), "missing"); + traced.hand_in(&mut s); + let e = s.execute(run.command(), run.params()).unwrap_err().to_string(); + assert!(e.contains("image data `img1` is missing"), "{e}"); + set_image_data(&mut s, "img1", Some(vec![])); + assert!(!run.current(&s), "empty"); + let empty = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap(); + assert!(empty.current(&s), "two empty blobs are equal"); + assert!(matches!(empty.run(&|_, _| true), Err(EngineError::Other(_)))); + assert!(matches!(s.execute(run.command(), run.params()), Err(EngineError::Other(_)))); +} + +/// Tracing an Image Trace object again follows the same rule: once the pixels of the image it +/// holds change, a run made before no longer applies, and the command traces the pixels there now. +#[test] +fn a_trace_run_of_an_image_trace_object_needs_its_pixels() { + let p = json!({"params": {"ignoreWhite": true}}); + let mut s = session(); + image_doc(&mut s); + let g = s.execute("imageTrace.make", &p).unwrap()["id"].as_u64().unwrap(); + let again = json!({"id": g, "params": {"ignoreWhite": true}}); + let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &again).unwrap(); + assert_eq!(run.target(), NodeId(g)); + let traced = run.run(&|_, _| true).unwrap(); + assert!(run.current(&s)); + set_image_data(&mut s, "img1", Some(moved_disc_png())); + assert!(!run.current(&s)); + traced.hand_in(&mut s); + let r = s.execute(run.command(), run.params()).unwrap(); + assert!(s.trace_hand_off.is_none(), "dropped"); + let x = traced_center_x(&s, &r); + assert!((x - 110.0).abs() < 1.5, "traced the pixels there now, at {x}"); +} + /// Shapes: the disc of the test image comes out as a live ellipse where the image lies, the same /// circle as its traced path; without the option it is a plain path. #[test] From 2361d2cb1b810bf32f60d5ff304fb6acc195e58b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:23:56 -0800 Subject: [PATCH 23/28] 3D: caps stay last when overlapping faces form a depth cycle - When the faces that overlap form a cycle of depth orders, the order broke the cycle only after drawing every face with nothing to wait for, so a cap could be drawn before the walls and they painted over it. A face drawn last now keeps its place: no face moves across it. - A face with a corner at or past the eye, which the perspective projection holds just in front of the eye, no longer gets a plane, so its depth is not measured on a plane its drawing does not match. - docs/three-d.md states the masked member rule in Groups as the Fills and strokes section does, and docs/target-app-parity.md cites the Inflate test by its name. --- crates/effects/src/solids.rs | 22 ++++++++++++++++----- crates/effects/src/solids/tests.rs | 31 ++++++++++++++++++++++++++++++ crates/three-d/src/solid/build.rs | 7 +++++-- crates/three-d/src/solid/tests.rs | 17 ++++++++++++++++ docs/target-app-parity.md | 2 +- docs/three-d.md | 7 +++++-- 6 files changed, 76 insertions(+), 10 deletions(-) diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index bd1e6e34ae..aeec471bcd 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -980,7 +980,8 @@ fn half(p: &[Point], values: &[f64], sign: f64) -> Vec { /// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each /// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays /// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`. -/// Otherwise `order` as it is. +/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place: +/// no face moves across it. Otherwise `order` as it is. fn local_order(faces: &[Placed], order: Vec) -> Vec { use std::cmp::Reverse; // The faces of each shape that take part, from left to right for a sweep along x. @@ -1065,14 +1066,25 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { // Each step draws the face that comes first in `order` of those whose faces before are drawn. let mut ready: std::collections::BinaryHeap> = (0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); + // The faces drawn last, in `order`: each goes only after every face before it in `order`. + let last: Vec = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect(); + let mut next_last = 0usize; let mut drawn = vec![false; faces.len()]; let mut out = Vec::with_capacity(order.len()); let mut first = 0usize; while out.len() < order.len() { - let k = match ready.pop() { - Some(Reverse((_, k))) => k, - None => { - // A cycle: the first face in `order` not drawn yet goes next. + while last.get(next_last).is_some_and(|&k| drawn[k]) { + next_last += 1; + } + let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]); + let k = match ready.peek() { + Some(&Reverse((at, k))) if at < limit => { + ready.pop(); + k + } + _ => { + // A cycle, or the faces left to draw before a face drawn last wait for faces after + // it: the first face in `order` not drawn yet goes next. while order.get(first).is_some_and(|&k| drawn[k]) { first += 1; } diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 3c2795dd1b..5126b76660 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -684,6 +684,37 @@ fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() { } } +/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap +/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at +/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer +/// than 0. 3 is the cap. +#[test] +fn a_depth_cycle_keeps_the_cap_last() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints: Paints::Other, + outline: square(x), + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let cap = Placed { + depth: f64::MAX, + side: false, + away: false, + bounds: Rect::new(0.0, 0.0, 18.0, 10.0), + member: 0, + paints: Paints::Other, + outline: vec![], + plane: None, + }; + let faces = [at(1.0, 0.0, [0.0, 0.0, 1.0], 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, [0.0, 0.0, 1.0], 1.0), cap]; + assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]); +} + /// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a /// face of the same shape's stroke drawn before it: the wall then goes just before that face. A /// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 1263582df9..359192c7f8 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -130,9 +130,12 @@ impl Builder<'_> { (V3(-n.0, -n.1, -n.2), false) }; // A face whose corners lie off one plane (a piece of a twisted wall bent into a saddle) has - // no plane to measure its depth on. + // no plane to measure its depth on. Nor has a face with a corner at or past the eye: the + // projection holds that corner just in front of the eye, so the drawing no longer matches + // the plane's projection there. let offset = n.dot(centre); - let flat = contours.iter().flatten().all(|v| (n.dot(*v) - offset).abs() <= 1e-3); + let held = self.camera.eye.is_some_and(|e| contours.iter().flatten().any(|v| e - v.2 < e * 1e-3)); + let flat = !held && contours.iter().flatten().all(|v| (n.dot(*v) - offset).abs() <= 1e-3); let plane = flat.then_some(DepthPlane { normal: [n.0, n.1, n.2], offset, center: self.camera.origin, eye: self.camera.eye }); #[cfg(test)] let view = contours.clone(); diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index b0c26ccc0a..9929a52860 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -177,6 +177,23 @@ fn a_flat_facet_measures_its_depth_on_its_plane() { } } +/// A flat face with a corner at or past the eye, which the projection holds just in front of the +/// eye, has no plane: its drawing no longer matches the plane's projection there. +#[test] +fn a_face_reaching_past_the_eye_has_no_plane() { + use super::build::{Builder, Order}; + let (_, b) = shape(&square(0.0, 0.0, 100.0)); + let camera = Camera::new(View { perspective: 50.0, ..front() }, b, 0.0); + let eye = camera.center_and_eye().1.unwrap(); + for (far, has_plane) in [(eye / 2.0, true), (2.0 * eye, false)] { + let mut builder = Builder { camera: &camera, closed: false, hidden: false, facets: vec![], mesh: None }; + let corners = vec![V3(-10.0, -10.0, 0.0), V3(10.0, -10.0, 0.0), V3(0.0, 10.0, far)]; + builder.face(vec![corners], V3(0.0, -far, 20.0), Order::Depth).unwrap(); + assert_eq!(builder.facets.len(), 1, "{far}"); + assert_eq!(builder.facets[0].plane.is_some(), has_plane, "{far}"); + } +} + #[test] fn a_bevel_inside_shrinks_the_cap_and_outside_grows_the_walls() { let (p, b) = shape(&square(0.0, 0.0, 100.0)); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f447b00c84..895708e987 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1176,7 +1176,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)). - A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`. - With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`. - - When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_cuts_its_dashes_as_a_white_one_does`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`. + - When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_draws_its_faces_in_one_order`, `solids::tests::a_depth_cycle_keeps_the_cap_last`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`. - Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715). - Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)). - Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`). diff --git a/docs/three-d.md b/docs/three-d.md index e9d5a696ff..71cced06b3 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -159,8 +159,11 @@ them all. The members stay editable: moving or editing one reshapes the solids. inside the 3D group applies to the solids of that group's members together. An opacity mask on a member masks its solids, and one on a group inside the 3D group masks the solids of that group's members together. The mask stays where it is on the page; it does not turn with the solids. A disabled mask is ignored. -- When a member, or a group inside the 3D group, has an opacity mask or a blending mode other than Normal, each - solid is drawn on its own, the backmost member's first, as when a solid is transparent. +- When a member, or a group inside the 3D group, has an opacity mask or a blending mode other than Normal, the + members' faces are not drawn in one shared order. Each member whose fills and strokes are opaque with Normal + blending draws their faces in one order of its own inside its masks and blending modes, as described under + [Fills and strokes](#fills-and-strokes). Otherwise each solid is drawn on its own, the backmost member's first, as + when a solid is transparent. - When every solid is opaque, all members' faces are drawn in one back-to-front order; otherwise each solid is drawn on its own, the backmost member's first. - Hidden members and guides are left out. A group holding a live object other than a blend (an envelope, a mesh, a From 8b990de0043b2e659886405a97cc429c3b9e52a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:25:49 -0800 Subject: [PATCH 24/28] Join: merge a run of coincident anchors in one pass over the path Join removed each merged anchor from the path's anchor list as it went, which moved every anchor after it, so a long selected run in front of many other anchors took time quadratic in the path's length. It also looked up each anchor's selection in the selected-anchor set. Join now marks the merged anchors and removes them in one pass at the end, reading the selection from one flag per anchor. Each corner or smooth conversion sees the same neighbors as before, so the resulting anchors are unchanged. Anchor::smooth_between holds the smoothing that SubPath::smooth_anchor applies. Tests compare the new merge bit for bit with the old one on 30,000 generated paths, and count the anchors moved when 300,000 selected anchors in front of 300,000 others merge: each of the others moves once. --- crates/engine/src/cmd/path.rs | 215 ++++++++++++++++++++++++++++++++-- crates/geom/src/path.rs | 36 +++--- docs/target-app-parity.md | 2 +- 3 files changed, 229 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index b4639f0de5..72484eda34 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -481,6 +481,12 @@ fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) { } } +#[cfg(test)] +thread_local! { + /// Anchors that [`merge_coincident`] moved to a lower index of their vector on this thread. + static ANCHOR_MOVES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which /// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many /// anchors went. @@ -501,23 +507,68 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: join_point(sp, 0, smooth); } } - // Back to front, so the indices `picked` knows stay true for the anchors still to visit. - for i in (1..sp.anchors.len()).rev() { + // Back to front, so the indices `picked` knows stay true for the anchors still to visit. A + // merged anchor is only marked here; the marked anchors are removed in one pass at the end. + let closed = sp.closed; + let anchors = &mut sp.anchors; + let len = anchors.len(); + let mut gone = vec![false; len]; + // The anchor after `i` that is still on the path, and the last one still on it. + let mut next = None; + let mut last = len.saturating_sub(1); + for i in (1..len).rev() { if picked(i - 1) && picked(i) - && let Some([a, b]) = sp.anchors.get_mut(i - 1..=i) + && let Some([a, b]) = anchors.get_mut(i - 1..=i) && same(a, b) { a.h_out = b.h_out; - sp.anchors.remove(i); - if let Some(smooth) = join_kind { - join_point(sp, i - 1, smooth); + if let Some(slot) = gone.get_mut(i) { + *slot = true; } + if next.is_none() { + last = i - 1; + } + if let Some(smooth) = join_kind { + // The neighbors the anchor has on the path as it now stands, as `join_point` sees them. + let prev = if i > 1 { Some(i - 2) } else { closed.then_some(last) }; + let after = next.or(closed.then_some(0)); + join_point_between(anchors, i - 1, prev, after, smooth); + } + } else { + next = Some(i); } } + #[cfg(test)] + if let Some(first) = gone.iter().position(|&g| g) { + // `retain` moves each anchor it keeps after the first one it drops. + let dropped = gone.iter().filter(|&&g| g).count(); + ANCHOR_MOVES.set(ANCHOR_MOVES.get() + (len - first - dropped)); + } + if gone.contains(&true) { + let mut k = 0; + anchors.retain(|_| { + let keep = !gone.get(k).copied().unwrap_or(false); + k += 1; + keep + }); + } before - sp.anchors.len() } +/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index. +fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option, next: Option, smooth: bool) { + let at = |j: Option| j.and_then(|j| anchors.get(j)).map(|a| a.p); + let (prev, next) = (at(prev), at(next)); + if let Some(a) = anchors.get_mut(ai) { + if smooth { + a.smooth_between(prev, next); + } else { + a.retract(); + } + } +} + /// Close subpath `si` of path `id`, merging coincident endpoints if present. fn close_subpath_in_node(d: &mut Document, id: NodeId, si: usize, join_kind: Option) -> Result<()> { let path = path_mut(d, id)?; @@ -751,8 +802,19 @@ pub(super) fn join(s: &mut Session, p: &Value) -> Result { let mut merged = vec![]; for (id, picked) in &st.selection.anchors { let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; - let n: usize = - path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum(); + // One flag per anchor; references past the end of a subpath or to a missing one pick nothing. + let mut masks: Vec> = path.subpaths.iter().map(|sp| vec![false; sp.anchors.len()]).collect(); + for &(si, ai) in picked { + if let Some(flag) = masks.get_mut(si).and_then(|m| m.get_mut(ai)) { + *flag = true; + } + } + let n: usize = path + .subpaths + .iter_mut() + .zip(&masks) + .map(|(sp, mask)| merge_coincident(sp, |ai| mask.get(ai).copied().unwrap_or(false), join_kind)) + .sum(); if n > 0 { merged.push((*id, path)); } @@ -1763,3 +1825,140 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result { })?; Ok(super::draw2::ids_json(&ids)) } + +#[cfg(test)] +mod tests { + use super::*; + + /// `merge_coincident` removing each merged anchor from the vector straight away, kept as the + /// reference the one-pass version must match. + fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option) -> usize { + let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6; + let before = sp.anchors.len(); + if sp.closed + && before > 2 + && picked(0) + && picked(before - 1) + && let [first, .., last] = sp.anchors.as_mut_slice() + && same(first, last) + { + first.h_in = last.h_in; + sp.anchors.pop(); + if let Some(smooth) = join_kind { + join_point(sp, 0, smooth); + } + } + for i in (1..sp.anchors.len()).rev() { + if picked(i - 1) + && picked(i) + && let Some([a, b]) = sp.anchors.get_mut(i - 1..=i) + && same(a, b) + { + a.h_out = b.h_out; + sp.anchors.remove(i); + if let Some(smooth) = join_kind { + join_point(sp, i - 1, smooth); + } + } + } + before - sp.anchors.len() + } + + /// Every field of every anchor, bit for bit. + fn bits(sp: &SubPath) -> (Vec<[u64; 6]>, Vec, bool) { + let b = |p: Point| [p.x.to_bits(), p.y.to_bits()]; + let fields = sp.anchors.iter().map(|a| [b(a.p), b(a.h_in), b(a.h_out)].concat().try_into().unwrap()).collect(); + (fields, sp.anchors.iter().map(|a| a.kind).collect(), sp.closed) + } + + /// A small linear congruential generator, so the cases are the same on every run. + struct Lcg(u64); + impl Lcg { + fn below(&mut self, n: u64) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) % n + } + } + + fn same_as_removal(sp: &SubPath, picked: &dyn Fn(usize) -> bool, join_kind: Option) { + let (mut ours, mut theirs) = (sp.clone(), sp.clone()); + let n = merge_coincident(&mut ours, picked, join_kind); + let m = merge_coincident_by_removal(&mut theirs, picked, join_kind); + assert_eq!(n, m, "{sp:?} {join_kind:?}"); + assert_eq!(bits(&ours), bits(&theirs), "{sp:?} {join_kind:?}"); + } + + /// Short paths with points on, near and just past the merge distance, selections with stale + /// indices, every anchor kind and every join kind give the same anchors, bit for bit, as + /// removing each merged anchor straight away. + #[test] + fn merging_coincident_anchors_matches_removing_them_one_by_one() { + let spots = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (5e-7, 0.0), (0.0, 1.5e-6), (10.0, 0.0), (5.0, 5.0), (10.0, 0.0)]; + let mut rng = Lcg(7); + for _ in 0..30_000 { + let n = rng.below(9) as usize; + let anchors = (0..n) + .map(|_| { + let (x, y) = spots[rng.below(spots.len() as u64) as usize]; + let p = Point::new(x, y); + let handle = |rng: &mut Lcg| match rng.below(3) { + 0 => p, + _ => p + Vec2::new(rng.below(7) as f64 - 3.0, rng.below(7) as f64 - 3.0), + }; + let (h_in, h_out) = (handle(&mut rng), handle(&mut rng)); + let kind = if rng.below(2) == 0 { AnchorKind::Corner } else { AnchorKind::Smooth }; + Anchor { p, h_in, h_out, kind } + }) + .collect(); + let sp = SubPath::new(anchors, rng.below(2) == 0); + let picks: Vec = (0..n + 2).map(|_| rng.below(4) != 0).collect(); + let join_kind = [None, Some(false), Some(true)][rng.below(3) as usize]; + same_as_removal(&sp, &|i| picks.get(i).copied().unwrap_or(false), join_kind); + } + } + + /// A smooth join of three anchors on one another takes the outgoing handle the middle anchor + /// was given when it joined the right one: an already smooth left anchor keeps that handle. + #[test] + fn a_smooth_join_of_three_anchors_keeps_the_handle_the_middle_one_got() { + let o = Point::ZERO; + let left = Anchor { p: o, h_in: Point::new(-2.0, 0.0), h_out: o, kind: AnchorKind::Smooth }; + let right = Anchor { p: o, h_in: o, h_out: Point::new(0.0, 5.0), kind: AnchorKind::Corner }; + let mut sp = SubPath::new(vec![left, Anchor::corner(o), right, Anchor::corner(Point::new(10.0, 0.0))], false); + assert_eq!(merge_coincident(&mut sp, |i| i < 3, Some(true)), 2); + let a = sp.anchors[0]; + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(-2.0, 0.0), Point::new(10.0 / 3.0, 0.0), AnchorKind::Smooth)); + assert_eq!(sp.anchors.len(), 2); + } + + /// One long run of selected anchors on one another, open or closed, becomes one anchor. + #[test] + fn a_long_run_of_anchors_on_one_another_becomes_one() { + for closed in [false, true] { + for join_kind in [None, Some(false), Some(true)] { + let anchors = (0..50_000).map(|i| Anchor::smooth(Point::ZERO, Point::new(1.0, i as f64))).collect(); + let sp = SubPath::new(anchors, closed); + same_as_removal(&sp, &|_| true, join_kind); + let mut ours = sp.clone(); + assert_eq!(merge_coincident(&mut ours, |_| true, join_kind), 49_999); + assert_eq!((ours.anchors.len(), ours.closed), (1, closed)); + } + } + } + + /// A long selected run at the start of a path followed by as many anchors that stay: each + /// anchor after the run moves once, not once per merged anchor. + #[test] + fn a_long_run_before_many_other_anchors_merges_in_one_pass() { + let run = 300_000; + let anchors = (0..run).map(|_| Anchor::corner(Point::ZERO)).chain((1..=run).map(|i| Anchor::corner(Point::new(i as f64, 1.0)))).collect(); + let mut sp = SubPath::new(anchors, false); + ANCHOR_MOVES.set(0); + assert_eq!(merge_coincident(&mut sp, |i| i < run, Some(false)), run - 1); + assert_eq!(ANCHOR_MOVES.get(), run); + assert_eq!(sp.anchors.len(), run + 1); + assert_eq!(sp.anchors[0].p, Point::ZERO); + assert_eq!(sp.anchors[1].p, Point::new(1.0, 1.0)); + assert_eq!(sp.anchors[run].p, Point::new(run as f64, 1.0)); + } +} diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 59a8f30660..af5a82c274 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -165,6 +165,26 @@ impl Anchor { pub fn reversed(&self) -> Self { Self { p: self.p, h_in: self.h_out, h_out: self.h_in, kind: self.kind } } + /// Make the anchor smooth between the points `prev` and `next` (its own point for a missing + /// one): handles in line with them, each a third of the way to that side's point. A smooth + /// anchor with both handles keeps them. False, with no change, when the two points give no + /// direction. [`SubPath::smooth_anchor`] calls it with the anchor's neighbors. + pub fn smooth_between(&mut self, prev: Option, next: Option) -> bool { + if self.kind == AnchorKind::Smooth && self.has_in() && self.has_out() { + return true; + } + let (pp, nn) = (prev.unwrap_or(self.p), next.unwrap_or(self.p)); + let dir = nn - pp; + let l = dir.hypot(); + if l <= 1e-9 { + return false; + } + let u = dir / l; + self.h_in = self.p - u * (self.p.distance(pp) / 3.0); + self.h_out = self.p + u * (self.p.distance(nn) / 3.0); + self.kind = AnchorKind::Smooth; + true + } /// Remove both handles (convert to a sharp corner). pub fn retract(&mut self) { self.h_in = self.p; @@ -398,21 +418,7 @@ impl SubPath { }; let at = |j: Option| j.and_then(|j| self.anchors.get(j)).map(|a| a.p); let (prev, next) = (at(prev), at(next)); - let Some(a) = self.anchors.get_mut(i) else { return false }; - if a.kind == AnchorKind::Smooth && a.has_in() && a.has_out() { - return true; - } - let (pp, nn) = (prev.unwrap_or(a.p), next.unwrap_or(a.p)); - let dir = nn - pp; - let l = dir.hypot(); - if l <= 1e-9 { - return false; - } - let u = dir / l; - a.h_in = a.p - u * (a.p.distance(pp) / 3.0); - a.h_out = a.p + u * (a.p.distance(nn) / 3.0); - a.kind = AnchorKind::Smooth; - true + self.anchors.get_mut(i).is_some_and(|a| a.smooth_between(prev, next)) } /// Cut at the anchors `at`: each becomes the end of one open piece and the start of the next, /// its handle off each piece retracted (the shape doesn't change). A closed subpath opens at diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..2103c2f9d4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1056,7 +1056,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile and arrowheads turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`). - - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. + - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command, the Eyedropper, a graphic style, Default Fill and Stroke or Swap Fill and Stroke, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph or Appearance controls, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out. From 393078b4f256203da3802411995d03dca16255eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:28:12 -0800 Subject: [PATCH 25/28] .ai export: a .ai of the art's bounds carries no editing data document.export and document.serialize to .ai with useArtboards: false wrote the one page of the visible art, but embedded the one-artboard stand-in as the native document and as the editing copy for other apps. Reopened, the file replaced the document's artboards with one artboard around the art. - The .ai of the art's bounds now leaves out both editing copies and returns the warning "Preserve editing was left out: an .ai file of the art's bounds would replace the document's artboards when reopened", as the PDF of the art's bounds does. - useArtboards: false with pdfCompatible: false is refused, with or without editingData, since the file would have blank pages and no editing copy. - Save, Save As, Save a Copy and exports of the artboards keep both copies. Legacy version 7 .ai files are written as before. Docs: docs/mcp.md, docs/target-app-parity.md, document.export params. --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/encode.rs | 7 ++ crates/engine/src/cmd/fileio/save.rs | 33 ++++++++- crates/engine/src/cmd/fileio/tests_pdfedit.rs | 71 +++++++++++++++---- docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 6 files changed, 105 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 26272d873d..752dcbef42 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 31539ff51d..0fbffcea82 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -629,6 +629,13 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { { return Ok(Encoded::one_with_notes(bytes, notes)); } + // So does a `.ai` file of the art's bounds (a legacy version 7 `.ai` file has none to leave out). + if use_artboards == Some(false) + && f.id == "ai" + && let Some(enc) = super::save::encode_ai_art_page(C, f, doc, p)? + { + return Ok(enc); + } if use_artboards == Some(false) && let Some((art, q)) = art_page(C, doc, p)? { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index e1cbf68bf2..777c7732a7 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -685,6 +685,31 @@ struct AiEditingData { editing_data: Option, } +/// Why a `.ai` file of the art's bounds (`useArtboards: false`) carries no editing data. +pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str = + "Preserve editing was left out: an .ai file of the art's bounds would replace the document's artboards when reopened"; + +/// The error for a `.ai` file of the art's bounds without PDF content. +pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false"; + +/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of +/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor +/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`]. +/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy +/// version 7 `.ai` file. +pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result> { + if super::encode::use_artboards(cmd, p)? != Some(false) || super::legacy_ai::wanted(cmd, f, p)? { + return Ok(None); + } + if !bool_or(p, "pdfCompatible", true) { + return Err(bad(cmd, ART_PAGE_NEEDS_PDF)); + } + let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) }; + let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?; + enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string()); + Ok(Some(enc)) +} + /// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file): /// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7 /// `.ai` files (`aiVersion: "7"`). @@ -692,9 +717,15 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res if super::legacy_ai::wanted(cmd, f, p)? { return super::legacy_ai::encode(cmd, f, doc, p); } + encode_ai_pages(cmd, f, doc, p, true) +} + +/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and +/// the editing copy for other apps when `editing` is true, and neither otherwise. +fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result { let mut params = if p.is_object() { p.clone() } else { json!({}) }; if let Some(o) = params.as_object_mut() { - o.insert("preserveEditing".into(), json!(true)); + o.insert("preserveEditing".into(), json!(editing)); // Keep upstream AI PDF layers, including hidden layers, unless a standard decides. if o.get("standard").is_none_or(Value::is_null) { o.entry("createLayers").or_insert(json!(true)); diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 2970238e38..0b560e5e04 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -402,28 +402,75 @@ fn ai_export_validates_options_even_when_editing_data_is_omitted() { } } -#[test] -fn ai_export_without_artboards_keeps_art_outside_the_original_pages() { +/// Two artboards, a visible 30 × 20 pt rectangle outside them at (180, 100) and a hidden one. +fn art_outside_the_artboards() -> Session { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 2})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("shape.rectangle", &json!({"x": 180, "y": 100, "width": 30, "height": 20})).unwrap(); s.execute("shape.rectangle", &json!({"x": 1000, "y": 1000, "width": 50, "height": 40})).unwrap(); s.execute("object.hide", &json!({})).unwrap(); + s +} + +/// Whether the `.ai` file `bytes` carries the editing copy of its art for other apps. +fn carries_private_data(bytes: &[u8]) -> bool { + let opts = LoadOptions { native: false, ..Default::default() }; + load::load_with("a.ai", bytes, &opts).unwrap().editing_data +} + +#[test] +fn an_ai_of_the_arts_bounds_carries_no_editing_data() { + let mut s = art_outside_the_artboards(); let before = comparable(&s.doc().unwrap().doc); - let r = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "range": "2"})).unwrap(); - let bytes = b64(&r); - let pages = vectorcraft_pdf::import(&bytes).unwrap(); - assert_eq!(pages.artboards.len(), 1); - assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0)); - let editing = vectorcraft_pdf::editing(&bytes).unwrap(); - let exported = vectorcraft_format::load(&editing.data).unwrap(); - assert_eq!(exported.artboards.len(), 1); - assert_eq!(exported.artboards[0].rect, vectorcraft_geom::Rect::new(180.0, 100.0, 210.0, 120.0)); - assert_eq!(comparable(&s.doc().unwrap().doc), before); + let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS); + let path = tmp("art-bounds.ai"); + for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] { + let mut params = json!({"format": "ai", "useArtboards": false}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = s.execute("document.export", ¶ms).unwrap(); + let bytes = if params.get("path").is_some() { std::fs::read(&path).unwrap() } else { b64(&r) }; + // One page, the visible art's bounds, whatever range names. + let pages = vectorcraft_pdf::import(&bytes).unwrap(); + assert_eq!(pages.artboards.len(), 1, "{params}"); + assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0), "{params}"); + assert!(vectorcraft_pdf::editing(&bytes).is_none(), "{params}"); + assert!(!carries_private_data(&bytes), "{params}"); + assert!(left_out(&r), "{params}: {r}"); + assert_eq!(comparable(&s.doc().unwrap().doc), before); + } + // The artboards keep both editing copies, without the warning. + for params in [json!({"format": "ai"}), json!({"format": "ai", "useArtboards": true})] { + let r = s.execute("document.export", ¶ms).unwrap(); + let bytes = b64(&r); + let editing = vectorcraft_pdf::editing(&bytes).expect("editing data"); + assert_eq!(vectorcraft_format::load(&editing.data).unwrap().artboards.len(), 2, "{params}"); + assert!(carries_private_data(&bytes), "{params}"); + assert!(!left_out(&r), "{params}: {r}"); + } assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err()); } +#[test] +fn an_ai_of_the_arts_bounds_without_pdf_is_refused() { + let mut s = art_outside_the_artboards(); + let before = comparable(&s.doc().unwrap().doc); + for extra in [json!({}), json!({"editingData": false}), json!({"editingData": true})] { + for command in ["document.export", "document.serialize"] { + let mut params = json!({"format": "ai", "useArtboards": false, "pdfCompatible": false}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let e = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(e.contains(super::save::ART_PAGE_NEEDS_PDF), "{command} {params}: {e}"); + assert_eq!(comparable(&s.doc().unwrap().doc), before); + } + } + // A document with no visible art is still refused for that. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap(); + let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false})).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); +} + /// Color Halftone's Max Radius is in pixels of the raster effects resolution since document /// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from /// before that opens with the radius converted, drawing the same dots; one saved since opens as diff --git a/docs/mcp.md b/docs/mcp.md index 41e28969f4..349704bfc6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -969,7 +969,11 @@ SVG writes one file per artboard of a `range`); `useArtboards: false` exports th its effects paint, the effects of groups, type and images included. `artboard.fitToArt` measures the art the same way. `document.exportPdf {useArtboards: false}` writes that one page as well, and ignores `artboard`, `artboards` and `range`. A PDF of that page, from either command, carries no Preserve Editing data; when Preserve Editing is on (as it -is in VectorCraft Default), the export comes back with a warning that says so. +is in VectorCraft Default), the export comes back with a warning that says so. A `.ai` export with +`useArtboards: false` writes that one page too, without the native document and without the editing copy for other +apps (`editingData`), and always comes back with the warning `Preserve editing was left out: an .ai file of the art's +bounds would replace the document's artboards when reopened`; with `pdfCompatible: false` it is refused, whatever +`editingData` says. A legacy version 7 `.ai` (`aiVersion: "7"`) of the art's bounds is written as before. Export As PDF continues in the Save PDF dialog with Use Artboards on or off; with it off, the dialog has no Artboards section and the page is the bounds of the visible art. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d9783b0216..dca049bc36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1577,6 +1577,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). The Save PDF dialog's "Write pages longer than 200 in at full size in points" (`longPagesInPoints`, off by default) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard. Export As PDF with Use Artboards off also opens the Save PDF dialog, without its Artboards section, and writes one page of the visible art's bounds with the dialog's options (`document.exportPdf {useArtboards: false}`; `crates/ui-egui/src/dialogs/tests_export.rs`, `crates/engine/src/cmd/fileio/tests_pdf.rs`). + A `.ai` export with Use Artboards off writes one page of the visible art's bounds without the native document or the editing copy for other apps, with a warning, so the file does not reopen with one artboard in place of the document's; without PDF content it is refused (`crates/engine/src/cmd/fileio/tests_pdfedit.rs`). PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. A PDF/A-2b export at PDF 1.4 with a page longer than 14,400 pt is written as PDF 1.6 with a `UserUnit` and a warning, whether or not `longPagesInPoints` is on, so its page boundaries stay within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13) unless the page is too narrow for that (`crates/pdf/src/tests/marks.rs`). PDF/X-1a, PDF/X-3 and PDF 1.3 files keep the art under the hidden part of a picture, gradient, pattern, mesh or raster effect that a clipping mask or clipping layer crops: flattening rasterizes only the part of such art that its clipping path shows, on its own page and on the next one. Layers the file leaves out are left out of the flattening, and transparent art that a clipping path hides entirely is removed (`crates/engine/src/cmd/fileio/tests_pdfx.rs`). From 358eb7fe7d2cbaee426dd63a8eb9fb25ccd3a4e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:41:08 -0800 Subject: [PATCH 26/28] Cursors: the Smooth entry lists the Paintbrush and Blob Brush Alt cases The cursor catalog's Smooth entry named only the Smooth tool and the Pencil with Alt key toggles to Smooth Tool on. The tools also show it for the Paintbrush with Alt held before a press while a path the Smooth tool can act on is selected, and for the Blob Brush with Alt held before a press or before the drag has moved, and through the drag that smooths. PaintbrushClose and Paintbrush now say that Alt before a press shows the closing ring only when no such path is selected. The gesture tests check that the Paintbrush shows Smooth through an Alt-press smoothing drag, with Alt let go too, and the closing ring for Alt pressed after a stroke begins with a smoothable path selected. --- crates/tools/src/cursors.toml | 6 ++++-- crates/tools/src/draw2/gesture/tests.rs | 12 ++++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 362262b488..4f1d123ae4 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -599,14 +599,14 @@ look = "PencilStraight's badge with a small filled square at the line's lower en [[cursor]] id = "Paintbrush" group = "Drawing and editing tools" -shown_when = ["The Paintbrush tool: draws a brushed freeform path (with pen pressure), continuing a selected path from its end; Alt closes it."] +shown_when = ["The Paintbrush tool: draws a brushed freeform path (with pen pressure), continuing a selected path from its end; Alt closes it, except that Alt held at the press with a path selected that the Smooth tool can act on smooths that path (see Smooth)."] hotspot = "The bristle tip." [[cursor]] id = "PaintbrushClose" group = "Drawing and editing tools" shown_when = [ - "The Paintbrush tool with Alt held, before a press and while drawing: releasing the mouse button with Alt still held closes the path.", + "The Paintbrush tool with Alt held while drawing, or before a press when no path is selected that the Smooth tool can act on (with one selected, Smooth shows): releasing the mouse button with Alt still held closes the path.", "The Paintbrush tool while a stroke is drawn back to within Close Paths When Ends Are Within of its start: releasing the mouse button there closes the path.", ] hotspot = "The bristle tip." @@ -632,6 +632,8 @@ group = "Drawing and editing tools" shown_when = [ "The Smooth tool: a drag along a selected path smooths it.", "The Pencil tool with Alt key toggles to Smooth Tool on: with Alt held before a stroke begins to draw, and through a drag that smooths.", + "The Paintbrush tool with Alt held before a press while a path is selected that the Smooth tool can act on (an editable path, not a guide, with three or more anchors on one of its subpaths), and through a drag that smooths.", + "The Blob Brush tool with Alt held before a press, or before the drag has moved from the press point, and through a drag that smooths.", ] hotspot = "The tip." diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index a0fe487289..567f6aee1f 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -1034,6 +1034,8 @@ fn paintbrush_alt_after_press_closes_without_smoothing_and_empty_selection_draws let selected_cx = cx(&d, &selected, &p); t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1)); t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Drag, pts[1].0, pts[1].1).with_mods(alt)); + // While drawing, Alt shows the closing ring though the selection could be smoothed. + assert_eq!(t.cursor(&selected_cx, Point::new(pts[1].0, pts[1].1), alt), Cursor::PaintbrushClose); let last = t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Up, pts[2].0, pts[2].1).with_mods(alt)); assert!(matches!(last.first(), Some(Action::Preview(c, v)) if c == "path.freehand" && v["closed"] == true), "{last:?}"); let cx = cx(&d, &empty, &p); @@ -1041,7 +1043,8 @@ fn paintbrush_alt_after_press_closes_without_smoothing_and_empty_selection_draws assert!(matches!(last.last().and_then(|a| a.first()), Some(Action::Preview(c, v)) if c == "path.freehand" && v["closed"] == true), "{last:?}"); } -/// The Paintbrush shows Smooth before an Alt press only with a selected path. +/// The Paintbrush shows Smooth before an Alt press only with a selected path, and through the +/// drag that smooths it, with Alt let go too. #[test] fn paintbrush_alt_cursor_matches_selection_at_press() { let (d, id) = doc_with_rect(); @@ -1050,9 +1053,14 @@ fn paintbrush_alt_cursor_matches_selection_at_press() { let empty = Selection::default(); let p = paint(); let alt = Mods { alt: true, ..Default::default() }; - let t = GestureTool::new("paintbrush"); + let mut t = GestureTool::new("paintbrush"); assert_eq!(t.cursor(&cx(&d, &selected, &p), Point::new(50.0, 150.0), alt), Cursor::Smooth); assert_eq!(t.cursor(&cx(&d, &empty, &p), Point::new(50.0, 150.0), alt), Cursor::PaintbrushClose); + let selected_cx = cx(&d, &selected, &p); + t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); + t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0).with_mods(alt)); + assert_eq!(t.cursor(&selected_cx, Point::new(150.0, 150.0), alt), Cursor::Smooth); + assert_eq!(t.cursor(&selected_cx, Point::new(150.0, 150.0), Mods::default()), Cursor::Smooth); } /// A selected text object leaves Alt Paintbrush drawing a closed stroke with its close cursor. From 5741c7bba0b6c418dccebbc3b6b0898adeb0c5f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:44:19 -0800 Subject: [PATCH 27/28] Color: assigned profiles follow the document in front The profiles Edit > Assign Profile gives a document stayed the active color settings after another document came to the front, so a new, opened or switched-to document drew and converted its colors through the previous document's profile, and closing the last document left it in use. The session now puts the front document's profiles in use (the working spaces where it has none, or no document is open) after a new or opened document, a tab switch, a close, File > Revert, every command including each batch step and Undo or Redo of Assign Profile, a failed batch or plug-in call, a script's rollback and slice boundaries, a canceled preview, undo group or undo scope, and for each document Export All Open and the update of placed documents work in. The active settings are rebuilt, and the documents redrawn, only when they change. --- crates/engine/src/cmd/addons/document.rs | 5 +- crates/engine/src/cmd/colormgmt.rs | 10 ++- crates/engine/src/cmd/fileio/batch.rs | 1 + crates/engine/src/cmd/links.rs | 5 +- crates/engine/src/cmd/plugin_call.rs | 1 + crates/engine/src/script/mod.rs | 5 ++ crates/engine/src/session/documents.rs | 17 +++- crates/engine/src/session/edit.rs | 4 + crates/engine/src/session/execute.rs | 4 + crates/engine/src/session/undo.rs | 6 ++ crates/engine/tests/color_settings.rs | 100 +++++++++++++++++++++++ docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 13 files changed, 156 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 654138a1dd..68681b50fa 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -132,8 +132,10 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result { let active = s.active; for i in 0..s.docs.len() { // Each document in turn is the one Save a Copy writes; switching tabs this way leaves every - // document's tool and interaction alone, and the active one comes back below. + // document's tool and interaction alone, and the active one comes back below. Its colors + // are written through its own profiles. s.active = Some(i); + s.sync_front_profiles(); let Ok(st) = s.doc() else { continue }; let title = st.doc.title.clone(); let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title)); @@ -160,6 +162,7 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result { } } s.active = active; + s.sync_front_profiles(); Ok(json!({ "files": files, "failed": failed, "format": format.id })) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 16990fc2ea..6c75eae128 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -5,9 +5,11 @@ //! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`, //! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in //! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and -//! take the place of the working spaces in the active settings when assigned, and when the working -//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay -//! as Edit → Color Settings set them. +//! take the place of the working spaces in the active settings while the document is in front +//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the +//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert, +//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color +//! Settings set them. use std::collections::BTreeMap; use std::sync::Arc; @@ -181,7 +183,7 @@ fn touch_all(s: &mut Session) { /// Make the active settings the working settings with the profiles the front document is assigned /// in place of the working spaces (none, or no document open: the working spaces). The open /// documents redraw when the active settings change. -fn use_front_profiles(s: &mut Session) { +pub(crate) fn use_front_profiles(s: &mut Session) { let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default(); if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) { touch_all(s); diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 18bc78b5d9..5bda9c06e2 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -41,6 +41,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { roll_back(s, start, &stash); s.notify_text_tool("batch.rollBack"); s.active = active; + s.sync_front_profiles(); (s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved; s.pending_paint = None; return Err(e); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index e3e72861b9..7df71e7422 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1331,14 +1331,17 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) { if targets.is_empty() { return; } - // Each document is updated as the active one, without switching tools. + // Each document is updated as the active one, through its own profiles, without switching + // tools. let back = s.active; for i in targets { s.active = Some(i); + s.sync_front_profiles(); // A file that can't be read leaves what its objects show: links.check reports it. let _ = update_where(s, None, Some(&path)); } s.active = back; + s.sync_front_profiles(); } // ---------- relative paths ---------- diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index f4b91edd9b..71fbcc8540 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -413,6 +413,7 @@ pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess st.interaction = None; } saved.restore(s); + s.sync_front_profiles(); Err(e) } } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 53f6e18f75..6a43b001d6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -672,6 +672,7 @@ impl Savepoint { s.pending_paint = self.pending_paint; self.choices.put(s); s.journal.truncate(self.journal); + s.sync_front_profiles(); exact } } @@ -2199,6 +2200,9 @@ fn failure_text(report: &Value) -> String { fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result, String> { let depth = std::mem::replace(&mut s.depth, 0); job.world.swap(s); + // The run's front document draws and converts through its own profiles, and the interface's + // again after the slice. + s.sync_front_profiles(); s.script_in_run = true; let cell = job.host.session.clone(); std::mem::swap(s, &mut *cell.borrow_mut()); @@ -2221,6 +2225,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() && !sets_in_any(t, &names)), - None => self.sync_opened_composite_fonts(index), + None => { + self.sync_opened_composite_fonts(index); + self.sync_front_profiles(); + } } true } @@ -403,6 +417,7 @@ impl Session { } self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) }; self.sync_front_composite_fonts(); + self.sync_front_profiles(); true } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 3d0d9ba1c6..4d0df82644 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -311,6 +311,8 @@ impl Session { self.paint = paint.clone(); } self.pending_paint = None; + // The previous preview's Assign Profile is undone with it. + self.sync_front_profiles(); let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params)); let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p)); // A selected object's converted appearance must not replace the current paints while @@ -436,6 +438,8 @@ impl Session { st.undo_interaction(); // Guides locked and slices locked or hidden during the interaction stay deselected. deselect_hidden(&menu, &st.doc, &mut st.selection); + // A canceled preview's Assign Profile is undone with it. + self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as // the document has it again, not as a preview left it. self.inherit_new_art(); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 23079fe901..7509c7740c 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -168,6 +168,10 @@ impl Session { let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs()); let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::>()); let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) }; + // Colors are drawn and converted through the profiles of the document in front now, also + // after an undone or redone Assign Profile, a failed or panicked command's documents put + // back, and a batch step, before the next step converts through them. + self.sync_front_profiles(); if r.is_err() && self.depth == 0 { self.batch_paint_docs.clear(); // A failed or panicked command's documents are put back: type is drawn in their diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index d06934926c..3af4cafe5f 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -164,6 +164,10 @@ impl Session { if self.depth == 0 { self.trim_histories(); } + // A canceled group's Assign Profile is undone with it. + if cancel { + self.sync_front_profiles(); + } } /// When journal entry `n` is a `command.batch` with `steps` noted in canceled undo groups and @@ -280,5 +284,7 @@ impl Session { g.journal.retain(|&(n, _)| n < scope.journal); g.steps.retain(|&(n, _)| n < scope.journal); } + // A canceled scope's Assign Profile is undone with it. + self.sync_front_profiles(); } } diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 6c7e90a188..fe56377d4e 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -180,6 +180,106 @@ fn a_batch_converts_through_the_profile_it_assigns() { assert_eq!(converted, fill(&device, b)); } +/// The profiles a document is assigned are in use while it is in front: a new or opened document +/// assigned none draws through the working spaces, switching back to the assigned document puts its +/// profile in use again, and closing a document puts the profiles of the document left in front, or +/// with none open the working spaces, in use. +#[test] +fn assigned_profiles_follow_the_front_document() { + let _g = settings(); + let dir = fresh_dir("front-profiles"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let tagged = dir.join("tagged.vectorcraft"); + let mut s = session(); + let working = cms::working_settings(); + assert_ne!(working.cmyk, cms::DEVICE_CMYK); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + exec(&mut s, "file.saveAs", json!({"path": tagged.to_str().unwrap()})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + assert_eq!(cms::active_settings(), working, "a new document draws through the working spaces"); + exec(&mut s, "document.activate", json!({"index": 0})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "back in front, the document draws through its profile"); + assert!(s.set_active(1)); + assert_eq!(cms::active_settings(), working, "a tab switch to the untagged document"); + exec(&mut s, "file.close", json!({})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "the document left in front draws through its profile"); + exec(&mut s, "file.close", json!({})); + assert_eq!(cms::active_settings(), working, "no document open: the working spaces"); + exec(&mut s, "document.open", json!({"path": tagged.to_str().unwrap()})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "an opened document draws through its saved profile"); +} + +/// Undo and Redo of Assign Profile, and File › Revert to a file assigned no profile, put the +/// profiles the document has then in use. +#[test] +fn undo_redo_and_revert_put_the_document_profiles_in_use() { + let _g = settings(); + let dir = fresh_dir("undo-profiles"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let untagged = dir.join("untagged.vectorcraft"); + let mut s = session(); + let working = cms::working_settings(); + exec(&mut s, "file.saveAs", json!({"path": untagged.to_str().unwrap()})); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK); + exec(&mut s, "edit.undo", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working, "undone: the working spaces"); + exec(&mut s, "edit.redo", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, Some(cms::DEVICE_CMYK.to_string()))); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "redone: the assigned profile"); + exec(&mut s, "file.revert", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working, "reverted: the working spaces"); +} + +/// A batch that assigns a profile and then fails puts the document back without it, and the +/// working spaces back in use. +#[test] +fn a_failed_batch_puts_the_profiles_in_use_back() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let working = cms::working_settings(); + let steps = json!([ + {"command": "edit.assignProfile", "params": {"cmyk": cms::DEVICE_CMYK}}, + {"command": "document.activate", "params": {"index": 99}}, + ]); + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working); +} + +/// A batch step that switches documents makes the next step convert through the profiles of the +/// document it switched to, not those of the document the batch began in. +#[test] +fn a_batch_converts_the_document_it_switches_to_through_its_profiles() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let blue = |s: &mut Session| { + let id = rect(s, 10.0, 10.0, 50.0, 50.0); + exec(s, "paint.setFill", json!({"ids": [id.0], "color": "#3366cc"})); + id + }; + let fill = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color(); + let mut working = session(); + let w = blue(&mut working); + exec(&mut working, "file.documentColorMode", json!({"mode": "cmyk"})); + let mut s = session(); + let b = blue(&mut s); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + let steps = json!([ + {"command": "document.activate", "params": {"index": 0}}, + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + ]); + exec(&mut s, "command.batch", json!({"commands": steps})); + assert_eq!(s.active_index(), Some(0)); + assert_eq!(fill(&s, b), fill(&working, w), "converted through the working CMYK space"); +} + /// View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in a /// document assigned another CMYK profile, in Proof Colors and in Separations Preview, and a change /// of the working CMYK space shows in the next proof while the document keeps its profile. diff --git a/docs/mcp.md b/docs/mcp.md index 41e28969f4..c4f5a9a575 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1434,8 +1434,10 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR start, after the profiles above are registered (#6335). Saved settings that name a profile that is no longer there, or a damaged file, leave the defaults (logged), and the next change writes over the file. `edit.assignProfile` tags the document only: colors show and convert through the profiles it assigns, and the - working spaces and the file stay as they are. The `workingCmyk` target of `view.proofSetup` simulates the working - CMYK space in such a document too. + working spaces and the file stay as they are. The profiles in use are those of the document in front, after + `file.new`, `document.open`, `document.activate`, `file.close`, `file.revert`, `edit.undo`, `edit.redo` and a + failed `command.batch` too; with none assigned, or no document open, the working spaces are. The `workingCmyk` + target of `view.proofSetup` simulates the working CMYK space in such a document too. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d9783b0216..11f0b4fa1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -703,7 +703,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`. -- **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. +- **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). From 98ea3231faecf17ee16b332f17601c820ddaa4d5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:44:41 -0800 Subject: [PATCH 28/28] Tests: the vectorcraft-mcp tests remove the temp folders they create The MCP unit tests wrote their files into one folder per process under the temp dir (vectorcraft-mcp-test-, vectorcraft-mcp-fileio-, testkit's mcp-cancel folder) and nothing removed them. The export-as and links tests removed their folder at the end, so a failing test left it. Each test that writes files now holds a TempFolder, a folder of its own that starts empty and is removed with everything in it when the test ends, also when it panics, as the findfiles tests' Tree guard does (crates/engine/src/cmd/findfiles/tests.rs:49). A new test checks that a leftover folder is emptied and that the folder is removed on drop and after a panic. --- crates/mcp/src/tests.rs | 88 ++++++++++++++++++++++++----- crates/mcp/src/tests/concurrency.rs | 5 +- crates/mcp/src/tests/exportas.rs | 12 ++-- crates/mcp/src/tests/fileio.rs | 81 ++++++++++++++------------ crates/mcp/src/tests/links.rs | 7 +-- 5 files changed, 127 insertions(+), 66 deletions(-) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index ffb6fcb93e..6529cf175d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -45,10 +45,62 @@ fn text_of(result: &Value) -> String { result["content"].as_array().unwrap().iter().filter(|c| c["type"] == "text").map(|c| c["text"].as_str().unwrap().to_string()).collect() } -fn tmp(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir.join(name) +/// A test's own folder under the temp dir, `vectorcraft-mcp--`, made empty when created +/// and removed with everything in it when dropped, also when the test panics. A removal that fails +/// (a file still open) is ignored. +struct TempFolder(std::path::PathBuf); + +impl TempFolder { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + /// The path of `name` in the folder. + fn file(&self, name: &str) -> std::path::PathBuf { + self.0.join(name) + } +} + +impl std::ops::Deref for TempFolder { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A `TempFolder` starts empty, and dropping it removes it with the files and folders in it, also +/// when the test that holds it panics. +#[test] +fn temp_folders_start_empty_and_are_removed_when_dropped() { + let leftover = std::env::temp_dir().join(format!("vectorcraft-mcp-drop-check-{}", std::process::id())); + std::fs::create_dir_all(&leftover).unwrap(); + std::fs::write(leftover.join("old.txt"), b"old").unwrap(); + let dir = TempFolder::new("drop-check"); + assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), 0, "a leftover folder is emptied"); + std::fs::write(dir.file("a.txt"), b"a").unwrap(); + std::fs::create_dir(dir.file("sub")).unwrap(); + std::fs::write(dir.file("sub").join("b.txt"), b"b").unwrap(); + let path = dir.to_path_buf(); + drop(dir); + assert!(!path.exists(), "{} is removed", path.display()); + + let panicked = std::panic::catch_unwind(|| { + let dir = TempFolder::new("panic-check"); + std::fs::write(dir.file("a.txt"), b"a").unwrap(); + panic!("the test fails with {} in use", dir.display()); + }); + assert!(panicked.is_err()); + let path = std::env::temp_dir().join(format!("vectorcraft-mcp-panic-check-{}", std::process::id())); + assert!(!path.exists(), "{} is removed after a panic", path.display()); } // ---------- framing ---------- @@ -286,6 +338,7 @@ fn headless_command_list_includes_ui_commands() { #[test] fn headless_end_to_end() { + let dir = TempFolder::new("headless-end-to-end"); let mut s = server(); rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION})); s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#); @@ -334,7 +387,7 @@ fn headless_end_to_end() { assert_eq!(call(&mut s, 44, "doc_inspect", json!({"ids": [999_999]}))["isError"], true); // Screenshot returns image content (base64 PNG) and text. - let shot_path = tmp("shot.png"); + let shot_path = dir.file("shot.png"); let r = call(&mut s, 5, "screenshot", json!({"path": shot_path.to_str().unwrap()})); assert_eq!(r["isError"], false, "{r}"); let img = r["content"].as_array().unwrap().iter().find(|c| c["type"] == "image").expect("image content"); @@ -344,14 +397,14 @@ fn headless_end_to_end() { assert_eq!(std::fs::read(&shot_path).unwrap(), png); // Export SVG. - let svg_path = tmp("out.svg"); + let svg_path = dir.file("out.svg"); let r = call(&mut s, 6, "export", json!({"path": svg_path.to_str().unwrap()})); assert_eq!(r["isError"], false, "{r}"); let svg = std::fs::read_to_string(&svg_path).unwrap(); assert!(svg.contains(" image::Rgb([220, 30, 30]), (35..55, 5..35) => image::Rgb([30, 60, 200]), @@ -441,8 +495,9 @@ fn trace_and_style_prompt_steps_run_in_order() { /// result, as exports do. The image is a dark disc (r = 30 px) on blue, traced with Ignore White. #[test] fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() { + let dir = TempFolder::new("trace-views"); let mut s = server(); - let png = tmp("trace-views.png"); + let png = dir.file("trace-views.png"); image::RgbImage::from_fn(100, 100, |x, y| { let (dx, dy) = (f64::from(x) + 0.5 - 50.0, f64::from(y) + 0.5 - 50.0); if dx * dx + dy * dy <= 900.0 { image::Rgb([0, 0, 0]) } else { image::Rgb([170, 210, 255]) } @@ -490,6 +545,7 @@ fn screenshot_and_render_preview_draw_the_trace_view_with_trace_views() { #[test] fn headless_path_gesture_undo() { + let dir = TempFolder::new("path-gesture-undo"); let mut s = server(); let count = |s: &mut Server| -> u64 { let r = call(s, 90, "inspect_document", json!({})); @@ -543,9 +599,9 @@ fn headless_path_gesture_undo() { assert_eq!(r["isError"], false, "{r}"); let r = call(&mut s, 11, "select_tool", json!({"tool": "pen"})); assert_eq!(r["isError"], false, "{r}"); - let r = call(&mut s, 12, "export", json!({"path": tmp("x.png").to_str().unwrap(), "scale": 0.5})); + let r = call(&mut s, 12, "export", json!({"path": dir.file("x.png").to_str().unwrap(), "scale": 0.5})); assert_eq!(r["isError"], false, "{r}"); - assert_eq!(&std::fs::read(tmp("x.png")).unwrap()[..4], b"\x89PNG"); + assert_eq!(&std::fs::read(dir.file("x.png")).unwrap()[..4], b"\x89PNG"); } /// A hover's reply comes once the tool's highlight is ready, also when the tool finds it on another @@ -1074,8 +1130,9 @@ fn relative_to_cwd(p: &std::path::Path) -> Option { #[test] fn headless_file_tools_take_relative_paths() { + let dir = TempFolder::new("relative-paths"); let mut s = server(); - let file = tmp("relative.vectorcraft"); + let file = dir.file("relative.vectorcraft"); let Some(rel) = relative_to_cwd(&file) else { return }; let rel = rel.to_str().unwrap(); assert!(std::path::Path::new(rel).is_relative()); @@ -1547,13 +1604,14 @@ fn text_effect_pathfinder_transform_graph_and_wrap_tools() { #[test] fn oversized_screenshot_and_png_export_are_errors() { // 16383 pt at the maximum scale (16) is 262 128 px a side: an error result, not a crashed server. + let dir = TempFolder::new("oversized-export"); let mut s = server(); let r = call(&mut s, 1, "run_command", json!({"command": "file.new", "params": {"width": 16383, "height": 16383}})); assert_eq!(r["isError"], false, "{r}"); let r = call(&mut s, 2, "screenshot", json!({"scale": 16})); assert_eq!(r["isError"], true, "{r}"); assert!(text_of(&r).contains("pixels"), "{r}"); - let path = tmp("huge.png"); + let path = dir.file("huge.png"); let r = call(&mut s, 3, "export", json!({"path": path.to_str().unwrap(), "scale": 16})); assert_eq!(r["isError"], true, "{r}"); assert!(!path.exists()); diff --git a/crates/mcp/src/tests/concurrency.rs b/crates/mcp/src/tests/concurrency.rs index d291d1e9fe..8e244b4eb0 100644 --- a/crates/mcp/src/tests/concurrency.rs +++ b/crates/mcp/src/tests/concurrency.rs @@ -10,6 +10,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_engine::cancel; +use super::TempFolder; use crate::{Backend, Server}; /// A backend whose `engine.execute` runs until cancelled (or for `limit`), like a long export. @@ -318,8 +319,8 @@ impl Backend for Gated { #[test] fn a_cancelled_export_through_the_real_engine_writes_nothing_and_leaves_the_session_usable() { - let path = vectorcraft_testkit::temp_dir("mcp-cancel").join("out.pdf"); - std::fs::remove_file(&path).ok(); + let dir = TempFolder::new("cancel"); + let path = dir.file("out.pdf"); let (read, mut to_server) = std::io::pipe().unwrap(); let (tx, replies) = mpsc::channel(); let (started_tx, started) = mpsc::channel(); diff --git a/crates/mcp/src/tests/exportas.rs b/crates/mcp/src/tests/exportas.rs index bc6e422d70..f46956bab8 100644 --- a/crates/mcp/src/tests/exportas.rs +++ b/crates/mcp/src/tests/exportas.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; +use super::TempFolder; use crate::{Backend, Headless, call_tool}; fn text(r: &crate::ToolResult) -> Value { @@ -48,9 +49,7 @@ fn an_option_no_format_takes_is_an_error() { /// write anything. #[test] fn a_save_or_screens_option_no_format_takes_is_an_error() { - let dir = std::env::temp_dir().join(format!("vc-mcp-save-options-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let dir = TempFolder::new("save-options"); let mut h = Headless::new(); h.call("engine.execute", json!({"command": "file.new", "params": {"width": 50, "height": 30}})).unwrap(); let pdf = dir.join("a.pdf").to_string_lossy().into_owned(); @@ -71,9 +70,8 @@ fn a_save_or_screens_option_no_format_takes_is_an_error() { let e = h.call("engine.execute", json!({"command": "file.exportForScreens", "params": params})).unwrap_err(); assert!(e.contains(named), "file.exportForScreens: {e}"); } - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written"); + assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), 0, "nothing was written"); h.call("app.save", json!({"path": pdf})).unwrap(); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -97,8 +95,7 @@ fn raster_export_uses_document_resolution_unless_overridden() { #[test] fn export_with_a_range_writes_one_file_per_artboard() { let mut h = three_boards(); - let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-exportas-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = TempFolder::new("exportas"); let path = dir.join("icon.png").to_string_lossy().to_string(); let args = json!({"path": path, "range": "1, 3", "options": {"useArtboards": true, "ppi": 144, "background": "white"}}); let r = text(&call_tool(&mut h, "export", &args)); @@ -120,5 +117,4 @@ fn export_with_a_range_writes_one_file_per_artboard() { let r = text(&call_tool(&mut h, "export", &json!({"format": format, "range": "1, 3"}))); assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{format}: {r}"); } - let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index 39bcde8d2e..3a89588ecd 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -5,12 +5,12 @@ use std::io::{BufRead, BufReader, Write}; use serde_json::{Value, json}; +use super::TempFolder; use crate::{Backend, Headless, Remote, Server, call_tool, tool_definitions}; -fn tmp(name: &str) -> String { - let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-fileio-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir.join(name).to_string_lossy().to_string() +/// The path of `name` in `dir`, as a string. +fn tmp(dir: &TempFolder, name: &str) -> String { + dir.file(name).to_string_lossy().to_string() } fn text(r: &crate::ToolResult) -> Value { @@ -29,22 +29,23 @@ fn two_boards() -> Headless { #[test] fn headless_opens_pdf_ai_and_templates() { + let dir = TempFolder::new("fileio-open"); let mut h = two_boards(); let pdf = h.call("engine.execute", json!({"command": "document.serialize", "params": {"format": "pdf"}})).unwrap(); let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap(); for name in ["x.pdf", "x.ai"] { - let path = tmp(name); + let path = tmp(&dir, name); std::fs::write(&path, &pdf).unwrap(); let r = text(&call_tool(&mut h, "open_file", &json!({"path": path}))); assert_eq!(r["title"], name); assert_eq!(h.session.doc().unwrap().doc.artboards.len(), 2, "one artboard per page"); } - let ait = tmp("x.ait"); + let ait = tmp(&dir, "x.ait"); std::fs::write(&ait, &pdf).unwrap(); let r = text(&call_tool(&mut h, "open_file", &json!({"path": ait}))); assert!(r["title"].as_str().unwrap().starts_with("Untitled-"), "{r}"); - let saved = h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": tmp("t.vectorcraft")}})).unwrap(); - let tpl = tmp("t.vctemplate"); + let saved = h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": tmp(&dir, "t.vectorcraft")}})).unwrap(); + let tpl = tmp(&dir, "t.vctemplate"); assert_eq!(saved["path"], tpl.as_str(), "saved with the template's extension: {saved}"); let r = text(&call_tool(&mut h, "open_file", &json!({"path": tpl}))); assert!(r["title"].as_str().unwrap().starts_with("Untitled-"), "{r}"); @@ -147,10 +148,11 @@ fn the_raster_scale_leaves_other_formats_alone() { #[test] fn exporting_native_keeps_the_document_path() { + let dir = TempFolder::new("fileio-keep-path"); let mut h = two_boards(); - let doc = tmp("keep.vectorcraft"); + let doc = tmp(&dir, "keep.vectorcraft"); h.call("app.save", json!({"path": doc})).unwrap(); - let copy = tmp("copy.vectorcraft"); + let copy = tmp(&dir, "copy.vectorcraft"); let r = text(&call_tool(&mut h, "export", &json!({"path": copy}))); assert_eq!(r["format"], "vectorcraft"); assert_eq!(h.session.doc().unwrap().path.as_deref(), Some(doc.as_str())); @@ -167,9 +169,9 @@ fn exporting_native_keeps_the_document_path() { assert_eq!(h.session.doc().unwrap().path.as_deref(), Some(doc.as_str())); } -/// The bytes `save_file` writes to `name` with `args`. -fn saved_with(h: &mut Headless, name: &str, mut args: Value) -> Vec { - let path = tmp(name); +/// The bytes `save_file` writes to `name` in `dir` with `args`. +fn saved_with(h: &mut Headless, dir: &TempFolder, name: &str, mut args: Value) -> Vec { + let path = tmp(dir, name); args["path"] = json!(path); let r = text(&call_tool(h, "save_file", &args)); assert_eq!(r["format"], "vectorcraft", "{r}"); @@ -178,22 +180,23 @@ fn saved_with(h: &mut Headless, name: &str, mut args: Value) -> Vec { #[test] fn save_file_takes_the_native_save_options() { + let dir = TempFolder::new("fileio-save-options"); let mut h = two_boards(); - let gz = saved_with(&mut h, "gz.vectorcraft", json!({"compress": true})); + let gz = saved_with(&mut h, &dir, "gz.vectorcraft", json!({"compress": true})); assert_eq!(gz[..2], [0x1f, 0x8b], "gzipped"); - let plain = saved_with(&mut h, "plain.vectorcraft", json!({"compress": false})); + let plain = saved_with(&mut h, &dir, "plain.vectorcraft", json!({"compress": false})); assert_eq!(plain[0], b'{', "plain JSON"); let nodes = h.session.doc().unwrap().doc.node_count(); for name in ["gz.vectorcraft", "plain.vectorcraft"] { let mut back = Headless::new(); - text(&call_tool(&mut back, "open_file", &json!({"path": tmp(name)}))); + text(&call_tool(&mut back, "open_file", &json!({"path": tmp(&dir, name)}))); assert_eq!(back.session.doc().unwrap().doc.node_count(), nodes, "{name} reopens"); } - let opt = saved_with(&mut h, "opt.vectorcraft", json!({"options": {"compress": true}})); + let opt = saved_with(&mut h, &dir, "opt.vectorcraft", json!({"options": {"compress": true}})); assert_eq!(opt[..2], [0x1f, 0x8b], "`options` carries them too"); - let v3: Value = serde_json::from_slice(&saved_with(&mut h, "v3.vectorcraft", json!({"version": 3, "preview": null}))).unwrap(); + let v3: Value = serde_json::from_slice(&saved_with(&mut h, &dir, "v3.vectorcraft", json!({"version": 3, "preview": null}))).unwrap(); assert_eq!(v3["version"], 3); - let shown = saved_with(&mut h, "preview.vectorcraft", json!({"preview": true})); + let shown = saved_with(&mut h, &dir, "preview.vectorcraft", json!({"preview": true})); assert!(vectorcraft_format::preview(&shown).is_some(), "a preview"); assert!(vectorcraft_format::preview(&plain).is_none(), "off by default"); // `precision` rounds the path coordinates of that save only. @@ -201,12 +204,12 @@ fn save_file_takes_the_native_save_options() { p.call("engine.execute", json!({"command": "file.new", "params": {"width": 100, "height": 100}})).unwrap(); p.call("engine.execute", json!({"command": "path.create", "params": {"anchors": [{"x": 10.123456, "y": 20.654321}, {"x": 30.5, "y": 40.25}]}})) .unwrap(); - let exact = String::from_utf8(saved_with(&mut p, "exact.vectorcraft", json!({"compress": false}))).unwrap(); + let exact = String::from_utf8(saved_with(&mut p, &dir, "exact.vectorcraft", json!({"compress": false}))).unwrap(); assert!(exact.contains("10.123456") && exact.contains("20.654321"), "{exact}"); - let rounded = String::from_utf8(saved_with(&mut p, "rounded.vectorcraft", json!({"compress": false, "precision": 1}))).unwrap(); + let rounded = String::from_utf8(saved_with(&mut p, &dir, "rounded.vectorcraft", json!({"compress": false, "precision": 1}))).unwrap(); assert!(!rounded.contains("10.123456") && !rounded.contains("20.654321") && rounded.contains("20.7"), "{rounded}"); // Version 2 files can't be compressed: the engine's error comes back. - let r = call_tool(&mut h, "save_file", &json!({"path": tmp("v2.vectorcraft"), "version": 2, "compress": true})); + let r = call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "v2.vectorcraft"), "version": 2, "compress": true})); assert!(r.is_error && r.content[0]["text"].as_str().unwrap().contains("can't be compressed"), "{r:?}"); // The options are in the schema; a misspelled one is still refused. @@ -214,9 +217,9 @@ fn save_file_takes_the_native_save_options() { let call = |s: &mut Server, args: Value| { s.handle(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "save_file", "arguments": args}})).unwrap() }; - let r = call(&mut s, json!({"path": tmp("ok.vectorcraft"), "compress": true})); + let r = call(&mut s, json!({"path": tmp(&dir, "ok.vectorcraft"), "compress": true})); assert_eq!(r["result"]["isError"], false, "{r}"); - let r = call(&mut s, json!({"path": tmp("typo.vectorcraft"), "compresss": true})); + let r = call(&mut s, json!({"path": tmp(&dir, "typo.vectorcraft"), "compresss": true})); assert_eq!(r["error"]["code"], -32602, "{r}"); assert!(r["error"]["message"].as_str().unwrap().contains("unknown argument `compresss`"), "{r}"); } @@ -225,12 +228,13 @@ fn save_file_takes_the_native_save_options() { /// that disagrees with the same key in `options` is an error. #[test] fn save_file_warns_about_options_it_does_not_use() { + let dir = TempFolder::new("fileio-unused-options"); let mut h = two_boards(); let warnings = |r: &Value| -> Vec { r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect() }; let ignored = |w: &[String], key: &str| w.iter().any(|w| w.starts_with(&format!("`{key}` was not used"))); // SVG reads none of them, at the top level or in `options`. - let path = tmp("ignored.svg"); + let path = tmp(&dir, "ignored.svg"); let r = text(&call_tool(&mut h, "save_file", &json!({"path": path, "compress": true, "version": 3, "options": {"preview": true}}))); assert_eq!(r["format"], "svg", "{r}"); let w = warnings(&r); @@ -239,16 +243,15 @@ fn save_file_warns_about_options_it_does_not_use() { assert!(w.iter().any(|w| w.contains("SVG")), "names the format: {w:?}"); assert!(std::fs::read(&path).unwrap().starts_with(b"<"), "plain SVG"); // A .ai file reads `compress` but not `version`. - let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored.ai"), "compress": false, "version": 3}))); + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "ignored.ai"), "compress": false, "version": 3}))); let w = warnings(&r); assert!(ignored(&w, "version") && !ignored(&w, "compress"), "{w:?}"); // `precision` is read by native files only. - let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored-precision.svg"), "precision": 2}))); + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "ignored-precision.svg"), "precision": 2}))); assert!(ignored(&warnings(&r), "precision"), "{r}"); // A top-level value that disagrees with `options` is refused, and nothing is written. - let path = tmp("both.vectorcraft"); - let _ = std::fs::remove_file(&path); + let path = tmp(&dir, "both.vectorcraft"); let r = call_tool(&mut h, "save_file", &json!({"path": path, "compress": true, "options": {"compress": false}})); let e = r.content[0]["text"].as_str().unwrap(); assert!(r.is_error && e.contains("`compress: true` and `options.compress: false` disagree"), "{r:?}"); @@ -257,7 +260,7 @@ fn save_file_warns_about_options_it_does_not_use() { for mut args in [json!({"compress": true, "options": {"compress": true}}), json!({"compress": false, "version": 3, "preview": true, "precision": 4})] { - args["path"] = json!(tmp("quiet.vectorcraft")); + args["path"] = json!(tmp(&dir, "quiet.vectorcraft")); let r = text(&call_tool(&mut h, "save_file", &args)); assert_eq!(r["warnings"], json!([]), "{args}: {r}"); } @@ -286,6 +289,7 @@ fn save_file_warns_about_options_it_does_not_use() { /// when the save reuses the options the document was last saved with. #[test] fn save_file_notes_name_the_ai_file_it_writes() { + let dir = TempFolder::new("fileio-ai-notes"); let mut h = Headless::with_document(); let notes = |r: &Value| -> Vec { r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect() @@ -296,21 +300,22 @@ fn save_file_notes_name_the_ai_file_it_writes() { ("no-pdf.ai", json!({"pdfCompatible": false, "preview": true}), "non-PDF-compatible .ai"), ("pdf.ai", json!({"pdfCompatible": true, "preview": true}), "PDF-compatible .ai"), ] { - let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(name), "version": 3, "options": options}))); + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, name), "version": 3, "options": options}))); let expected = [format!("`version` was not used: {label} files don't read it"), format!("`options.preview` was not used: {label} files don't read it")]; assert_eq!(notes(&r), expected, "{name}: {r}"); } // A save given no option the file reads writes it as last saved: a legacy `.ai` again. - text(&call_tool(&mut h, "save_file", &json!({"path": tmp("again.ai"), "options": {"aiVersion": "7"}}))); - let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("again.ai"), "options": {"preview": true}}))); + text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "again.ai"), "options": {"aiVersion": "7"}}))); + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp(&dir, "again.ai"), "options": {"preview": true}}))); assert_eq!(notes(&r), ["`options.preview` was not used: legacy .ai (version 7) files don't read it"], "{r}"); - assert!(std::fs::read(tmp("again.ai")).unwrap().starts_with(b"%!PS"), "a legacy .ai is written"); + assert!(std::fs::read(tmp(&dir, "again.ai")).unwrap().starts_with(b"%!PS"), "a legacy .ai is written"); } #[test] fn save_file_is_the_same_call_in_the_app_and_headless() { - let path = tmp("app.vectorcraft"); + let dir = TempFolder::new("fileio-app-save"); + let path = tmp(&dir, "app.vectorcraft"); let (addr, app) = recording_app(); let mut remote = Remote::connect(&addr).unwrap(); let args = json!({"path": path, "compress": true, "version": 3, "preview": null, "precision": 2, "options": {"preview": true}}); @@ -392,7 +397,8 @@ fn pdf_pages(pdf: &[u8]) -> usize { /// only, in the document and in the exported PDF. #[test] fn document_color_mode_puts_rgb_greys_on_the_black_plate() { - let svg = tmp("greys.svg"); + let dir = TempFolder::new("fileio-greys"); + let svg = tmp(&dir, "greys.svg"); std::fs::write( &svg, r##" @@ -447,7 +453,8 @@ fn open_file_passes_the_importer_on() { let tools = tool_definitions(); let open = tools.iter().find(|t| t["name"] == "open_file").unwrap(); assert!(open["inputSchema"]["properties"].get("importer").is_some(), "{open}"); - let svg = tmp("importer.svg"); + let dir = TempFolder::new("fileio-importer"); + let svg = tmp(&dir, "importer.svg"); std::fs::write(&svg, r#""#).unwrap(); let mut h = Headless::new(); assert_eq!(text(&call_tool(&mut h, "open_file", &json!({"path": svg})))["format"], "svg"); diff --git a/crates/mcp/src/tests/links.rs b/crates/mcp/src/tests/links.rs index 20298fc612..61d660a8d8 100644 --- a/crates/mcp/src/tests/links.rs +++ b/crates/mcp/src/tests/links.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; +use super::TempFolder; use crate::{Headless, call_tool}; fn run(h: &mut Headless, command: &str, params: Value) -> Value { @@ -13,9 +14,8 @@ fn run(h: &mut Headless, command: &str, params: Value) -> Value { #[test] fn headless_links_report_missing_files_and_relink() { - let dir = std::env::temp_dir().join(format!("vectorcraft-mcp-links-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = |n: &str| dir.join(n).to_string_lossy().into_owned(); + let dir = TempFolder::new("links"); + let file = |n: &str| dir.file(n).to_string_lossy().into_owned(); let mut h = Headless::new(); run(&mut h, "file.new", json!({"width": 300, "height": 200})); let png = run(&mut h, "document.serialize", json!({"format": "png"})); @@ -30,5 +30,4 @@ fn headless_links_report_missing_files_and_relink() { let r = run(&mut h, "links.relink", json!({"ids": [id], "path": file("b.png")})); assert_eq!(r["relinked"], json!([id])); assert_eq!(run(&mut h, "links.check", json!({}))["links"][0]["status"], "ok"); - let _ = std::fs::remove_dir_all(dir); }