diff --git a/README.md b/README.md index 7e49943a31..b04c91e066 100644 --- a/README.md +++ b/README.md @@ -252,11 +252,12 @@ speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified The scores are self-assessed from our code against public documentation; [target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them. +All 57 approximated Photoshop-style raster filters are available. The Effect Gallery includes filter thumbnails and an in-dialog preview. + **What's missing:** - reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; - 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials); -- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in); - CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface); - scripting, and the rest of Variables (image and graph kinds, dataset import); - generative AI features. diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 04b48634ed..d49776b2cb 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -266,6 +266,7 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip /// (`opt.scope`) or on a locked artboard. On a layer whose Preview is off it counts by its /// outline, as a click there hits it. pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option { + let _walk = ArtWalk::open(); let symbols = doc.symbol_boxes(); let locks = doc.locked_artboards(); selected.iter().rev().copied().find(|&id| { @@ -322,6 +323,7 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option) -> Vec { + let walk = ArtWalk::open(); let opt = HitOptions { scope: scope.or(opt.scope), ..opt }; // Normally one hit test per *object* suffices: layers and sublayers aren't selectable, // while a group (including a clipping group) is selected as one object. Repeatedly @@ -337,6 +339,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option Vec { + let _walk = ArtWalk::open(); let symbols = doc.symbol_boxes(); let mut out = Vec::new(); if let Some(scope) = opt.scope @@ -506,6 +512,7 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab /// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art /// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints. fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option { + let _walk = ArtWalk::open(); let finish = |mut h: Hit| { h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents)); h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count(); @@ -1059,9 +1066,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } // A symbol instance is hit within its bounds, and outside them where its art paints - // ([`instance_art_hit`]). + // ([`instance_art_hit`]). In the art of another instance walked outside that instance's + // bounds, it is hit only where its own art paints ([`ArtOnly`]). NodeKind::SymbolInstance { .. } => { - if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { return Some(HitKind::Bounds); } instance_art_hit(n, p, opt, symbols) @@ -1172,6 +1180,15 @@ impl<'a> InstanceArt<'a> { whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes)) } + /// How many objects placing the whole art makes: the objects of the art with their opacity + /// masks' art ([`Node::count_with_masks`]), or, through the guides, the most that + /// [`crate::NineSliceMap::most_placed_with`] counts. + fn size(&self) -> u64 { + self.map + .as_ref() + .map_or_else(|| u64::try_from(self.art.count_with_masks()).unwrap_or(u64::MAX), |m| m.most_placed_with(&self.art, &self.boxes)) + } + /// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by /// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when /// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as @@ -1219,6 +1236,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or /// no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { + let _walk = ArtWalk::open(); let art = InstanceArt::of(doc, inst)?; let symbols = doc.symbol_boxes(); let mut path = vec![]; @@ -1250,7 +1268,7 @@ impl FindPart<'_> { /// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead /// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off. fn find(&self, n: &Node, path: &mut Vec, whole: Option, outline: bool) -> Option { - if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) { + if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || !ArtWalk::take(1) { return None; } let outline = outline || previews_off(n); @@ -1298,17 +1316,120 @@ impl FindPart<'_> { /// Outline, [`HitOptions::outline`]): its strokes, and the art that the live geometry effects of a /// clipping path in it show past the art's box. `None` for an instance of a missing symbol, of a /// symbol that holds an instance of itself or nests too deep ([`SymbolBoxes::art`]), and of art past -/// the 9-slice object limit ([`InstanceArt::of`]). +/// the 9-slice object limit ([`InstanceArt::of`]), when `p` is outside the instance's reach +/// ([`Node::reach_bounds_with`]), and once the click has visited as many objects of symbol art as +/// [`ArtWalk`] allows. fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None }; - if opt.outline || symbols.art(symbol).is_none() { + if opt.outline || symbols.art(symbol).is_none() || !n.reach_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + return None; + } + let _walk = ArtWalk::open(); + if ArtWalk::used_up() { return None; } let art = InstanceArt::of(symbols.document(), n)?; + #[cfg(test)] + ARTS_WALKED.with(|c| c.set(c.get() + 1)); let opt = HitOptions { clip_outlines: false, ..opt }; + let _art_only = ArtOnly::set(); FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false) } +thread_local! { + /// Whether a symbol instance's art is being walked outside the instance's box ([`ArtOnly`]). + static ART_ONLY: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While a guard lives, a symbol instance is hit ([`hit_leaf`]) and touched by a marquee +/// ([`marquee_with`]) only where its own art is, by the same rule at every level, and not anywhere +/// in its box. [`instance_art_hit`] and the marquee's walk of an instance's art hold one: they walk +/// the art outside the instance's box, where the box of an instance nested in the art can reach +/// past it over empty space. +struct ArtOnly { + was: bool, +} + +impl ArtOnly { + fn set() -> Self { + Self { was: ART_ONLY.replace(true) } + } + + fn on() -> bool { + ART_ONLY.get() + } +} + +impl Drop for ArtOnly { + fn drop(&mut self) { + ART_ONLY.set(self.was); + } +} + +thread_local! { + /// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]), + /// `None` outside one. + static ART_WALK_LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +thread_local! { + /// The number of objects [`ArtWalk::open`] allows on this thread in place of + /// [`crate::MAX_SYMBOL_NODES`]. + static ART_WALK_LIMIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// How many symbol instances' art clicks and marquees walked on this thread. + static ARTS_WALKED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The objects of symbol art that one click or one marquee may visit: [`crate::MAX_SYMBOL_NODES`] +/// in all, the art of the instances nested in that art included, at every level. The first +/// [`ArtWalk::open`] of a click or a marquee sets the limit, and the walks opened while its guard +/// lives share it. Once the limit is used up, an instance is no longer hit or touched outside its +/// box; inside its box it still is. +struct ArtWalk { + outermost: bool, +} + +impl ArtWalk { + fn open() -> Self { + let walk = Self { outermost: ART_WALK_LEFT.get().is_none() }; + walk.restart(); + walk + } + + /// For the outermost guard, sets what is left back to the whole limit. + fn restart(&self) { + if self.outermost { + #[cfg(test)] + let limit = ART_WALK_LIMIT.get().unwrap_or(crate::MAX_SYMBOL_NODES); + #[cfg(not(test))] + let limit = crate::MAX_SYMBOL_NODES; + ART_WALK_LEFT.set(Some(limit)); + } + } + + /// Is nothing left? + fn used_up() -> bool { + ART_WALK_LEFT.get() == Some(0) + } + + /// Takes `n` objects from what is left. `false` when fewer are left, and nothing is left after. + fn take(n: u64) -> bool { + let Some(left) = ART_WALK_LEFT.get() else { return true }; + let rest = left.checked_sub(n); + ART_WALK_LEFT.set(Some(rest.unwrap_or(0))); + rest.is_some() + } +} + +impl Drop for ArtWalk { + fn drop(&mut self) { + if self.outermost { + ART_WALK_LEFT.set(None); + } + } +} + /// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks /// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it /// does not count. @@ -1502,6 +1623,7 @@ fn previews_off(n: &Node) -> bool { } fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { + let _walk = ArtWalk::open(); let mut out = Vec::new(); // The objects the marquee may touch ([`Top`]). let tops: Vec = match scope.and_then(|s| doc.node(s)) { @@ -1613,8 +1735,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), // A symbol instance is touched by its box, and outside it where the live geometry - // effects of a clipping path in its art show the art. - NodeKind::SymbolInstance { .. } => box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), + // effects of a clipping path in its art show the art. In the art of another instance + // walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]). + NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), _ => box_touches(n, s, r), } } @@ -1628,15 +1751,26 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } /// Does the marquee `r` touch the art of symbol instance `n` placed as the canvas draws it, as /// it touches a group of that art? Only for art whose clipping paths have live geometry effects - /// ([`SymbolBoxes::art`]), and only when `r` meets the instance's reach - /// ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's box. + /// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the + /// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's + /// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows. fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false }; let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; - if s.art(symbol).is_none_or(|a| a.reshaped.is_none()) || !n.reach_bounds_with(s).is_some_and(meets) { + if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) { + return false; + } + let _walk = ArtWalk::open(); + if ArtWalk::used_up() { return false; } let Some(art) = InstanceArt::of(s.document(), n) else { return false }; + if !ArtWalk::take(art.size()) { + return false; + } + #[cfg(test)] + ARTS_WALKED.with(|c| c.set(c.get() + 1)); + let _art_only = ArtOnly::set(); art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false)) } fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 1c817f2bf1..74bd959a7f 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1961,6 +1961,185 @@ fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() { assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view"); } +/// Outside a symbol instance's box, an instance nested in its art counts where its own art is, not +/// anywhere in its box: a click or a marquee on empty space in the nested box, where a moved +/// clipping path shows the art past the outer box, selects nothing, and on art drawn there it +/// selects the outer instance. +#[test] +fn a_nested_symbol_instances_box_past_the_outer_box_is_not_a_hit() { + set_clip_region(moved_clip_region); + // `Two` draws squares at the corners of 0..200 × 0..100, and with `middle` one at 140..160 × + // 40..60. The outer symbol clips an instance of it to 0..100 × 0..100, which `test.move` moves + // to 100..200: the outer box is 0..100, the nested box 0..200. + let build = |middle: bool| { + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let square = |d: &mut Document, r: Rect| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art())); + let mut squares = vec![square(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)), square(&mut d, Rect::new(190.0, 90.0, 200.0, 100.0))]; + if middle { + squares.push(square(&mut d, Rect::new(140.0, 40.0, 160.0, 60.0))); + } + group_symbol(&mut d, "Two", squares); + let (mut mask, _) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let nested = instance_of(&mut d, "Two"); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), nested]); + clip.set_clips(true); + group_symbol(&mut d, "Outer", vec![Arc::new(clip)]); + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Outer".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + (d, inst) + }; + let at = |d: &Document, x: f64, y: f64| hit_test(d, Point::new(x, y), HitOptions::default()).map(|h| h.leaf); + let inside = Rect::new(145.0, 45.0, 155.0, 55.0); + let (d, inst) = build(false); + assert_eq!(at(&d, 150.0, 50.0), None, "empty space in the nested box"); + assert!(marquee(&d, inside, None, false).is_empty(), "marquee on empty space in the nested box"); + assert_eq!(at(&d, 195.0, 95.0), Some(inst), "on the nested art past the outer box"); + assert_eq!(at(&d, 50.0, 50.0), Some(inst), "in the outer box"); + let (d, inst) = build(true); + assert_eq!(at(&d, 150.0, 50.0), Some(inst), "on the nested art"); + // Across the middle square's left edge. + assert_eq!(marquee(&d, Rect::new(135.0, 45.0, 145.0, 55.0), None, false), [inst], "marquee on the nested art"); +} + +/// Adds the symbol `Clipped`: a clip group whose clipping path's region `test.move` moves to +/// 100..200 × 0..100, past the 0..100 box, over a 0..200 × 0..100 rectangle shown when `shown`. +/// A click at (150, 50) hits an instance of it on the rectangle, or, with the rectangle hidden, +/// walks its art and finds nothing. +fn clipped_symbol(d: &mut Document, shown: bool) { + set_clip_region(moved_clip_region); + let (mut mask, mut art) = half_clipped(d); + mask.appearance.effects.push(test_move()); + art.visible = shown; + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + let root = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + d.symbols.push(crate::Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(root) }); +} + +/// A symbol named `name` whose art is a group of `members`. +fn group_symbol(d: &mut Document, name: &str, members: Vec>) { + let root = Node::group(d.alloc_id(), members); + d.symbols.push(crate::Symbol { dynamic: false, name: name.into(), art: Arc::new(root) }); +} + +/// An instance of the symbol named `symbol`, not moved. +fn instance_of(d: &mut Document, symbol: &str) -> Arc { + Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY })) +} + +/// 30 small squares at the origin, which a click at (150, 50) passes by. +fn far_squares(d: &mut Document) -> Vec> { + (0..30).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()))).collect() +} + +/// Runs `f` with [`ArtWalk`] allowing `limit` objects, and returns its result with how many +/// leaves [`hit_leaf`] tested and how many instances' art was walked meanwhile. +fn with_art_limit(limit: u64, f: impl FnOnce() -> R) -> (R, usize, usize) { + ART_WALK_LIMIT.with(|c| c.set(Some(limit))); + LEAVES_TESTED.with(|c| c.set(0)); + ARTS_WALKED.with(|c| c.set(0)); + let r = f(); + ART_WALK_LIMIT.with(|c| c.set(None)); + (r, LEAVES_TESTED.with(std::cell::Cell::get), ARTS_WALKED.with(std::cell::Cell::get)) +} + +/// One click visits at most the art walk's limit of objects in a chain of nested symbol +/// instances, though each level's art alone is well within it. A click on the art of an +/// instance nested in another is still found. +#[test] +fn a_click_walks_a_chain_of_nested_symbol_instances_within_one_limit() { + // Level 0 is `Clipped`; each level above holds an instance of the level below and 30 squares: + // 32 objects to visit at each level. + let chain = |shown: bool| { + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + clipped_symbol(&mut d, shown); + for level in 1..12 { + let below = if level == 1 { "Clipped".to_string() } else { format!("Level {}", level - 1) }; + let mut members = vec![instance_of(&mut d, &below)]; + members.extend(far_squares(&mut d)); + group_symbol(&mut d, &format!("Level {level}"), members); + } + let inst = instance_of(&mut d, "Level 11"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + (d, id) + }; + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf); + // Without one limit for the click, the miss walks the art of all 12 levels. + let (d, inst) = chain(false); + let (hit, _, arts) = with_art_limit(100, || at(&d, 150.0)); + assert_eq!(hit, None); + assert!(arts <= 4, "{arts} levels walked"); + assert_eq!(with_art_limit(100, || at(&d, 50.0)).0, Some(inst), "in the box"); + // Past the limit, a click that the art would take finds only the box. + let (d, inst) = chain(true); + assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, None, "past the limit"); + assert_eq!(at(&d, 150.0), Some(inst), "within the limit"); + // Two levels: a click on the inner instance's art is found within the limit. + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + clipped_symbol(&mut d, true); + let inner = instance_of(&mut d, "Clipped"); + group_symbol(&mut d, "Outer", vec![inner]); + let inst = instance_of(&mut d, "Outer"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, Some(id), "nested"); +} + +/// One click, and one marquee, visit at most the art walk's limit of objects in art that repeats +/// one nested instance many times, though the art of each instance alone is well within it. A +/// click on one of the nested instances' art is still found. +#[test] +fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit() { + // 50 instances of `Clipped` in one symbol's art, its rectangle shown when `shown`. + let repeated = |shown: bool| { + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + clipped_symbol(&mut d, shown); + let members = (0..50).map(|_| instance_of(&mut d, "Clipped")).collect(); + group_symbol(&mut d, "Repeated", members); + let inst = instance_of(&mut d, "Repeated"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + (d, id) + }; + let (d, inst) = repeated(false); + // Without one limit for the click, the miss walks the art of all 51 instances. The outer art + // takes 1 object of the 100, and each nested instance with its art 4. + let (hit, _, arts) = with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf)); + assert_eq!(hit, None); + assert!(arts <= 26, "{arts} instances' art walked"); + // Select Behind over 60 instances of `Clipped` on the layer shares one limit too: each walk + // takes 3 objects of the 100. + let mut stack = Document::new(600.0, 400.0); + let l = stack.layers[0].id; + clipped_symbol(&mut stack, false); + for _ in 0..60 { + let inst = instance_of(&mut stack, "Clipped"); + stack.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + } + let (behind, _, arts) = with_art_limit(100, || objects_at(&stack, Point::new(150.0, 50.0), HitOptions::default(), None)); + assert!(behind.is_empty()); + assert!(arts <= 34, "Select Behind: {arts} instances' art walked"); + // Without one limit for the marquee, it places the art of all 51 instances, inside the moved + // region (within each instance's reach and outside its box). Placing the outer art takes 51 + // objects of the 100, and each nested art 4. + let inside = Rect::new(140.0, 40.0, 160.0, 60.0); + let (touched, _, arts) = with_art_limit(100, || marquee(&d, inside, None, false)); + assert!(touched.is_empty()); + assert!(arts <= 14, "{arts} instances' art placed"); + assert_eq!(with_art_limit(100, || marquee(&d, Rect::new(40.0, 40.0, 60.0, 60.0), None, false)).0, [inst], "in the box"); + // A click and a marquee on the nested instances' art are found within the limit. + let (d, inst) = repeated(true); + assert_eq!(with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf)).0, Some(inst), "click"); + let edge = Rect::new(140.0, -5.0, 160.0, 5.0); + assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 47b1c83206..a49e817ef2 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -171,7 +171,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) } } } - let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0)); + let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| crate::solids::shadow::casts(paint_of(i).1 * s.opacity))); return check_shadow(p, casting.map(|s| &s.path), b, options); } let (path, _) = object_profile(n, "Revolve")?; @@ -350,8 +350,8 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { /// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of /// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with -/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when -/// the surface it is cast from is past the limits. +/// the shadow off, when `item` is fully transparent or its opacity is not a finite number, or when +/// it casts nothing, and an error when the surface it is cast from is past the limits. /// /// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the /// surface is swept again for its shadow alone. @@ -366,7 +366,7 @@ fn shadow_of( ) -> Result, String> { let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) }; let (_, opacity, blend) = paint_of(item); - if opacity <= 0.0 { + if !crate::solids::shadow::casts(opacity) { return Ok(None); } let mut caster = vectorcraft_three_d::ShadowCaster::new(); @@ -377,7 +377,7 @@ fn shadow_of( /// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces /// its shadow is cast from ([`surface`])? fn casts(fx: &Effect, opacity: f32) -> bool { - opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some() + crate::solids::shadow::casts(opacity) && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some() } /// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was @@ -420,9 +420,9 @@ fn group_shadow( for s in shapes { let kept = kept.next().flatten(); let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue }; - // A member whose surface is fully transparent casts nothing. + // A member whose surface is fully transparent, or whose opacity is not a finite number, casts nothing. let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend }; - if ink.opacity <= 0.0 { + if !ink.casts() { continue; } let faces = cast_surface(&mut caster, &s.path, b, options, kept)?; @@ -1861,6 +1861,55 @@ mod tests { } } } + + /// A surface whose fill, or whose member, is at NaN or infinite opacity casts no shadow, as one + /// at 0 % does, whether the shadow is cast from the surface drawn or swept for it alone; the + /// member beside it still casts its part. + #[test] + fn a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow() { + let fx = crate::new_effect(REVOLVE, &json!({"shadow": true})).unwrap(); + let group = |opacity: f32| { + let mut other = profile_node(); + other.id = NodeId(2); + other.transform(Affine::translate((120.0, 0.0)), false); + other.opacity = opacity; + let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]); + g.appearance.effects.push(fx.clone()); + g + }; + let group_shadows = |g: &Node| { + let shapes = members(g, "").unwrap(); + let b = union_bounds(&shapes).unwrap(); + let options = shared_options(&shapes, fx_options(&fx)).unwrap(); + let kept: Vec> = shapes + .iter() + .map(|s| { + let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); + let cast = casts(&fx, opacity * s.opacity); + surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + }) + .collect(); + [group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()] + .map(|art| format!("{art:?}")) + }; + let expected = group_shadows(&group(0.0)); + for bad in [f32::NAN, f32::INFINITY] { + let mut n = profile_node(); + if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = bad; + } + let (path, _) = profile(&n).unwrap(); + let b = path.bounds().unwrap(); + let item = surface_item(&n.appearance.items).unwrap(); + assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow"); + let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); + assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn"); + assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone"); + let shadows = group_shadows(&group(bad)); + assert!(!expected[0].is_empty() && expected[0] != "[]", "the opaque member casts"); + assert_eq!(shadows, expected, "{bad}: only the opaque member casts"); + } + } } #[cfg(test)] diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 953768d298..cdc2376724 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1474,8 +1474,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result = vec![]; let ink = |item: &AppearanceItem, member: f32| { let (_, opacity, blend) = paint_of(item, member); @@ -1483,7 +1483,7 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result 0.0) { + for item in s.items.iter().filter(|i| ink(i, s.opacity).casts()) { let (area, rule) = region(&s.path, s.rule, item); #[cfg(test)] SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); @@ -1497,7 +1497,7 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result, String>> = if id == INFLATE { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); - let casts: Vec = inks.iter().map(|i| i.opacity > 0.0).collect(); + let casts: Vec = inks.iter().map(|i| i.casts()).collect(); #[cfg(test)] SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len())); caster.inflate(&shapes, &casts, bounds, inflate_options(p), view) @@ -1505,13 +1505,13 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result 0.0))); - added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); + SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts()))); + added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); } added }; for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) { - if ink.opacity <= 0.0 { + if !ink.casts() { continue; } // A stroke whose own solid is past the limits is left out; past the shadow's limit for @@ -1552,7 +1552,7 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec(id: &str, p: &Value, shapes: &'a [Profile], built: Vec = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect(); - if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) { + if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.casts() && kept.is_none())) { return cast_shadow(id, p, shapes); } for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) { - if ink.opacity <= 0.0 { + if !ink.casts() { continue; } let faces = match kept { diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs index 3906ac2d3c..81542a3722 100644 --- a/crates/effects/src/solids/shadow.rs +++ b/crates/effects/src/solids/shadow.rs @@ -50,6 +50,19 @@ pub(crate) struct Ink { pub(crate) blend: BlendMode, } +impl Ink { + /// Whether art in this ink casts part of a shadow ([`casts`]). + pub(crate) fn casts(self) -> bool { + casts(self.opacity) + } +} + +/// Whether art at `opacity` casts part of a shadow: its opacity is a finite number above zero. +/// Art at zero, negative, NaN or infinite opacity casts nothing. +pub(crate) fn casts(opacity: f32) -> bool { + opacity.is_finite() && opacity > 0.0 +} + /// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled /// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule; /// `None` when it casts nothing. diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 4d62961612..7dfd78f28d 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -312,3 +312,63 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() } } } + +/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art, +/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts +/// it from the faces the solids drawn kept. +fn cast_parts(n: &Node) -> [(Vec, String); 2] { + let (_, fx) = solid(&n.appearance.effects).unwrap(); + let shapes = if is_container(n) { + members(n, "").unwrap() + } else { + let (path, rule) = profile(n).unwrap(); + vec![Profile { path, rule, items: solid_paint_sources(n).1, opacity: 1.0, scopes: vec![] }] + }; + let p = crate::merged_params(&fx.id, &fx.params); + let (_, built) = surfaces_for(None, n, fx, &shapes, true).unwrap(); + [cast_shadow(&fx.id, &p, &shapes), cast_built(&fx.id, &p, &shapes, built)].map(|c| { + let (caster, settings, cast) = c.unwrap().unwrap(); + let inks = cast.iter().map(|(_, ink, _)| ink.opacity).collect(); + (inks, format!("{:?}", shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)))) + }) +} + +/// A fill, a stroke or a member whose opacity is NaN or infinite casts no part of the shadow, as one +/// at 0 % does, whether the shadow is cast from solids built for it or from the solids drawn; the +/// art beside it still casts its part. +#[test] +fn art_whose_opacity_is_not_a_finite_number_casts_no_shadow() { + // The art with opacity `opacity` in one place: a square's stroke, the fill of a group's second + // member, and a group's second member. + let objects = |opacity: f32| { + let mut fill = square_node(2, 200.0); + for item in &mut fill.appearance.items { + if let AppearanceItem::Fill(f) = item { + f.opacity = opacity; + } + } + let mut member = square_node(2, 200.0); + member.opacity = opacity; + [ + stroked_square(1, 0.0, opacity), + Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(fill)]), + Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(member)]), + ] + }; + for id in [EXTRUDE, INFLATE, ROTATE] { + for bad in [f32::NAN, f32::INFINITY] { + for (i, (mut n, mut clear)) in objects(bad).into_iter().zip(objects(0.0)).enumerate() { + n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + clear.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let expected = cast_parts(&clear); + for (k, (inks, shadow)) in cast_parts(&n).into_iter().enumerate() { + assert_eq!(inks, vec![1.0], "{id} {bad} object {i} cast {k}: only the opaque art casts"); + assert_eq!(shadow, expected[k].1, "{id} {bad} object {i} cast {k}"); + } + let mut opacities = vec![]; + art(&n, id).unwrap().walk(&mut |c| opacities.extend(shadow_opacity(c))); + assert_eq!(opacities, vec![0.5], "{id} {bad} object {i}"); + } + } + } +} diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 28cd71804a..fc5be365d5 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -54,6 +54,7 @@ pub mod ppi; pub mod progress; mod psdlayers; pub mod psdread; +mod psdslices; mod pxrread; mod save; mod screens; @@ -93,6 +94,9 @@ pub(crate) use native::preview_png; pub use native::with_compression_pref; pub(crate) use pdfimport::opened_page_document; pub use pdfimport::{LoadOptions, page_document}; +pub(crate) use psdlayers::import_active as psd_layers; +pub use psdlayers::{PsdInfo, info as psd_info}; +pub(crate) use psdslices::over as psd_slices; pub(crate) use save::job_for; pub(crate) use save::save as save_document; pub use save::{ @@ -240,6 +244,8 @@ mod tests_psd; mod tests_psdlayers; #[cfg(test)] mod tests_psdread; +#[cfg(test)] +mod tests_psdslices; #[cfg(test)] mod tests_heifread; diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 505c87cc8b..4a3ca6265a 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -1,6 +1,6 @@ use super::access::file_list; use super::formats::formats; -use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, save, screens}; +use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, psdlayers, save, screens}; pub fn specs() -> Vec { vec![ @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), @@ -139,6 +139,15 @@ pub fn specs() -> Vec { always, pdfimport::pdf_info ), + cmd!( + query "document.psdInfo", + "PSD Info", + [], + None, + "{path} or {name?, dataBase64} what a PSD or PSB file holds, read from its header, slices and layer records without decoding pixels → {format: psd|psb, width, height (the canvas, px), layers (group markers not counted), hiddenLayers (the hidden ones among them), groups, slices (those importSlices brings in; 0 when the file has none or they can't be read)}; a file without layer records, or whose layer records can't be read, has layers: 0 and opens and places as its merged image; a file that is not a PSD or PSB file is an error", + always, + psdlayers::psd_info + ), cmd!( "document.exportForOffice", "Save for Office Documents…", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 2ff393b685..52ed7f0e7f 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -528,17 +528,26 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } // A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with // `layers: false`, its merged image opens. Layers that can't be read leave the merged image. - "psd" | "psb" if opts.layers => { - let cms = vectorcraft_color::cms::active(); - match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) { - Ok(Some((doc, warnings))) => (doc, warnings, false), - Ok(None) => (raster_doc(&title, bytes)?, vec![], false), - Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false), - } - } + "psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) { + Ok(Some((doc, warnings))) => (doc, warnings, false), + Ok(None) => (raster_doc(&title, bytes)?, vec![], false), + Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false), + }, _ if format.raster => (raster_doc(&title, bytes)?, vec![], false), _ => return Err(err(format!("{} files can't be opened yet", format.label))), }; + // A PSD or PSB file's slices become user slices over its canvas (`importSlices`, default on), + // whether its layers or its merged image came in. + if matches!(format.id, "psd" | "psb") + && opts.import_slices + && let Some(canvas) = doc.artboards.first().map(|a| a.rect) + { + let (slices, notes) = super::psd_slices(bytes, canvas); + for (rect, options) in slices { + crate::cmd::slices::add_slice(&mut doc, rect, options); + } + warnings.extend(notes); + } // A PDF, `.ai` or `.ait` read from its pages or its editing copy, not restored from the document // it carries, opens with the File Info it gives (a PostScript `.ai` gives none). if matches!(format.id, "pdf" | "ai" | "ait") diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 00eef89a11..189274a31f 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -36,6 +36,8 @@ pub struct LoadOptions { pub layers: bool, /// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out). pub hidden_layers: bool, + /// A PSD or PSB file's slices become user slices (`importSlices`; else they are left out). + pub import_slices: bool, /// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]). pub dxf: vectorcraft_cad::ImportOptions, /// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its @@ -67,6 +69,7 @@ impl Default for LoadOptions { text_as: TextAs::default(), layers: true, hidden_layers: false, + import_slices: true, dxf: Default::default(), editing_data: true, trust_editing_data: false, @@ -81,7 +84,7 @@ impl LoadOptions { /// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when /// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`, /// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false), - /// `editingData` (true | false | `always`), + /// `importSlices` (true | false), `editingData` (true | false | `always`), /// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true | /// false) and `dxf` (the DXF import options). pub fn from_params(cmd: &str, p: &Value) -> Result { @@ -111,6 +114,10 @@ impl LoadOptions { None => false, Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?, }; + let import_slices = match p.get("importSlices").filter(|v| !v.is_null()) { + None => true, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "importSlices must be true or false"))?, + }; let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) { None => (true, false), Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true), @@ -137,6 +144,7 @@ impl LoadOptions { text_as, layers, hidden_layers, + import_slices, dxf, editing_data, trust_editing_data, diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index c3c45029a0..ea5cf63aa2 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -43,6 +43,7 @@ use std::cell::Cell; use std::sync::Arc; use image::RgbaImage; +use serde_json::{Value, json}; use vectorcraft_color::BlendMode; use vectorcraft_color::blend::{blend_rgb, composite}; use vectorcraft_color::cms::{Lab, lab::lab_to_srgb}; @@ -51,6 +52,7 @@ use vectorcraft_geom::Affine; use super::load::{RasterImage, as_png}; use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb}; +use crate::cmd::Session; use crate::cmd::place::text::mac_roman; /// Most layer groups inside one another. @@ -1527,3 +1529,65 @@ pub(super) fn import( doc.limit_depth_noting(&mut warnings); Ok(Some((doc, warnings))) } + +/// [`import`] within the memory allowed for one image, CMYK converted with the active color +/// settings: what `document.open` and `file.place` read a PSD or PSB file's layers with. +pub(crate) fn import_active(bytes: &[u8], hidden: bool) -> Result)>, String> { + let cms = vectorcraft_color::cms::active(); + import(bytes, hidden, super::MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) +} + +/// What a PSD or PSB file holds (`document.psdInfo`, the PSD Import Options dialog). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PsdInfo { + /// The large document format. + pub psb: bool, + /// The canvas, in pixels. + pub width: u32, + pub height: u32, + /// The layers, group markers left out. + pub layers: usize, + /// The layers among them that are hidden. + pub hidden: usize, + /// The layer groups. + pub groups: usize, + /// The slices that come in with `importSlices` (those generated automatically, and those + /// outside the canvas, left out). + pub slices: usize, +} + +/// What PSD or PSB file `bytes` holds, read from its header, its slices and its layer records +/// without decoding any pixels. A file without layer records, or whose layer records can't be read, has no layers: it +/// opens and places as its merged image. +pub fn info(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + let records = layer_info(h.layers, h.psb).filter(|info| info.len() > 2).and_then(|info| records(info, h.psb).ok()).unwrap_or_default(); + let layers = records.iter().filter(|r| r.divider == 0); + Ok(PsdInfo { + psb: h.psb, + width: h.width, + height: h.height, + layers: layers.clone().count(), + hidden: layers.filter(|r| r.hidden).count(), + groups: records.iter().filter(|r| matches!(r.divider, 1 | 2)).count(), + slices: super::psdslices::count(bytes), + }) +} + +const INFO: &str = "document.psdInfo"; + +/// `document.psdInfo`. +pub(super) fn psd_info(_: &mut Session, p: &Value) -> crate::cmd::Result { + let bytes = super::source(p, INFO)?.bytes; + let i = info(&bytes).map_err(super::load::err)?; + Ok(json!({ + "format": if i.psb { "psb" } else { "psd" }, + "width": i.width, + "height": i.height, + "layers": i.layers, + "hiddenLayers": i.hidden, + "groups": i.groups, + "slices": i.slices, + })) +} diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index 28b44d6197..ed9f08a731 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -105,7 +105,7 @@ pub(super) struct Header<'a> { /// Colour mode data: an indexed image's palette (256 reds, then greens, then blues). palette: &'a [u8], /// The image resources. - resources: &'a [u8], + pub(super) resources: &'a [u8], /// The layer and mask information. pub(super) layers: &'a [u8], } @@ -172,7 +172,7 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its /// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the /// blocks whose signature is `8BIM` are given. -fn resources(resources: &[u8], signed: bool) -> impl Iterator { +pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator { let mut r = Reader::new(resources); std::iter::from_fn(move || { if r.rest().is_empty() { diff --git a/crates/engine/src/cmd/fileio/psdslices.rs b/crates/engine/src/cmd/fileio/psdslices.rs new file mode 100644 index 0000000000..ea87f70797 --- /dev/null +++ b/crates/engine/src/cmd/fileio/psdslices.rs @@ -0,0 +1,408 @@ +//! The slices a Photoshop document (PSD or PSB) stores, for `document.open` and `file.place` +//! with `importSlices`: image resource 1050, read from the "Slices resource format" of Adobe's +//! public Photoshop File Formats Specification +//! (). Version 6 stores the slices +//! as records; versions 7 and 8 store them in a descriptor. The descriptor's keys, and the meaning +//! of the origin, type and background values, are read as the MIT-licensed ag-psd reads them +//! (, `src/imageResources.ts` and `src/descriptor.ts`), +//! which agrees with psd.rb (, +//! `lib/psd/resources/slices.rb`) on the keys both read. +//! +//! A slice the file marks as generated automatically is left out: the document lays out its own +//! auto slices around the others. A slice that follows a layer comes in as a user slice over the +//! rectangle the file stores for it. Each slice keeps its name, its type (Image or No Image), its +//! link, target, message, alternative text, cell text and background color; text alignment isn't +//! read. The file is untrusted: every read is checked, and the slice count, the strings and the +//! descriptor's nesting and item count are capped. + +use vectorcraft_doc::{SliceKind, SliceOptions}; +use vectorcraft_geom::Rect; + +use super::psdread::{Reader, TRUNCATED, header, resources}; + +/// The image resource that holds the slices. +const SLICES: u16 = 1050; + +/// The most slices one file brings in. +const MAX_SLICES: usize = 10_000; + +/// The deepest descriptor objects and lists nest. +const MAX_DEPTH: usize = 16; + +/// The most values the descriptors of one slices resource hold together, nested ones included. +const MAX_VALUES: usize = 200_000; + +/// The error of descriptors that hold more than [`MAX_VALUES`]. +const TOO_MANY_VALUES: &str = "the slices' descriptor holds too many values"; + +/// One slice as the file stores it. +#[derive(Clone, Debug, PartialEq)] +struct PsdSlice { + /// Left, top, right and bottom, in the canvas's pixels. + rect: [i64; 4], + options: SliceOptions, +} + +/// The slices a file stores, those generated automatically left out, and its canvas. +struct Stored { + slices: Vec, + /// The canvas's width and height, in pixels. + size: (u32, u32), +} + +/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050 +/// before the image resources end or are cut short). An error when the file isn't a PSD or PSB +/// file, or its slices can't be read. +fn read(bytes: &[u8]) -> Result, String> { + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + let Some((_, _, data)) = resources(h.resources, true).find(|(id, _, _)| *id == SLICES) else { return Ok(None) }; + Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) })) +} + +/// The slices of resource 1050's `data`. +fn decode(data: &[u8]) -> Result, String> { + let mut r = Reader::new(data); + // The values every descriptor of the resource may hold together. + let mut budget = MAX_VALUES; + match r.u32()? { + 6 => version_6(&mut r, &mut budget), + 7 | 8 => { + if r.u32()? != 16 { + return Err("the slices' descriptor has a version other than 16".into()); + } + let d = descriptor(&mut r, 0, &mut budget)?; + from_descriptor(&d) + } + v => Err(format!("the slices are stored in version {v}, which isn't read")), + } +} + +/// Version 6: the bounds of all the slices, the group's name, the count, then each slice's record. +/// The descriptors that follow the records spend one `budget` of values between them. +fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, String> { + r.take(16)?; + unicode(r)?; + let count = r.u32()? as usize; + if count > MAX_SLICES { + return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read")); + } + let mut out = vec![]; + for _ in 0..count { + // The ID and group ID. + r.take(8)?; + let origin = r.u32()?; + // A slice that follows a layer gives the layer's ID. + if origin == 1 { + r.take(4)?; + } + let name = unicode(r)?; + let kind = if r.u32()? == 0 { SliceKind::NoImage } else { SliceKind::Image }; + let mut rect = [0i64; 4]; + for v in &mut rect { + *v = i64::from(r.u32()? as i32); + } + let (url, target, message, alt) = (unicode(r)?, unicode(r)?, unicode(r)?, unicode(r)?); + let html = r.u8()? != 0; + let cell = unicode(r)?; + // The horizontal and vertical alignment. + r.take(8)?; + let [a, red, green, blue] = r.array::<4>()?; + let background = if a == 0 && red == 0 && green == 0 && blue == 0 { + String::new() + } else if a == 0 { + "matte".into() + } else { + format!("#{red:02x}{green:02x}{blue:02x}") + }; + // Photoshop 7 and later may follow a record with a descriptor (version 16); a record that + // doesn't start one is the next slice. A descriptor read that uses up the budget is an + // error. + if r.rest().starts_with(&16u32.to_be_bytes()) { + let mut ahead = Reader::new(r.rest()); + ahead.u32()?; + match descriptor(&mut ahead, 0, budget) { + Ok(_) => { + let used = r.rest().len() - ahead.rest().len(); + r.take(used)?; + } + Err(e) if e == TOO_MANY_VALUES => return Err(e), + Err(_) => {} + } + } + // Origin 0 is a slice generated automatically. + if origin != 0 { + let options = SliceOptions { kind, name, url, target, message, alt, text: cell_text(cell, html), background, ..Default::default() }; + out.push(PsdSlice { rect, options: for_kind(options) }); + } + } + Ok(out) +} + +/// Versions 7 and 8: the descriptor's `slices` list, each slice an object. +fn from_descriptor(d: &[(String, Value)]) -> Result, String> { + let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) }; + if list.len() > MAX_SLICES { + return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len())); + } + let mut out = vec![]; + for s in list { + let Value::Object(s) = s else { return Err("the slices' descriptor lists something other than a slice".into()) }; + if matches!(field(s, "origin"), Some(Value::Enum(_, v)) if v == "autoGenerated") { + continue; + } + let Some(Value::Object(b)) = field(s, "bounds") else { return Err("a slice in the slices' descriptor has no bounds".into()) }; + let edge = |k: &str| number(field(b, k)).ok_or_else(|| "a slice's bounds in the slices' descriptor aren't numbers".to_string()); + let rect = [edge("Left")?, edge("Top ")?, edge("Rght")?, edge("Btom")?]; + let text = |k: &str| match field(s, k) { + Some(Value::Text(t)) => t.clone(), + _ => String::new(), + }; + let kind = if matches!(field(s, "Type"), Some(Value::Enum(_, v)) if v == "noImage") { SliceKind::NoImage } else { SliceKind::Image }; + let html = matches!(field(s, "cellTextIsHTML"), Some(Value::Bool(true))); + let background = match field(s, "bgColorType") { + Some(Value::Enum(_, v)) if v == "matte" => "matte".into(), + Some(Value::Enum(_, v)) if v == "Clr " => match field(s, "bgColor") { + Some(Value::Object(c)) => { + let channel = |k: &str| number(field(c, k)).map(|v| v.clamp(0, 255)); + match (channel("Rd "), channel("Grn "), channel("Bl ")) { + (Some(r), Some(g), Some(b)) => format!("#{r:02x}{g:02x}{b:02x}"), + _ => String::new(), + } + } + _ => String::new(), + }, + _ => String::new(), + }; + let options = SliceOptions { + kind, + name: text("Nm "), + url: text("url"), + target: text("null"), + message: text("Msge"), + alt: text("altTag"), + text: cell_text(text("cellText"), html), + background, + ..Default::default() + }; + out.push(PsdSlice { rect, options: for_kind(options) }); + } + Ok(out) +} + +/// `o` with only the options of its slice type: an Image slice's cell text isn't shown, and a No +/// Image slice has no link, target, message or alternative text. +fn for_kind(mut o: SliceOptions) -> SliceOptions { + if o.kind == SliceKind::Image { + o.text.clear(); + } else { + for s in [&mut o.url, &mut o.target, &mut o.message, &mut o.alt] { + s.clear(); + } + } + o +} + +/// A cell's text as the HTML a No Image slice shows: plain text has `&`, `<` and `>` escaped. +fn cell_text(text: String, html: bool) -> String { + if html { text } else { text.replace('&', "&").replace('<', "<").replace('>', ">") } +} + +/// The longest text one string, key or class ID holds (UTF-16 units or bytes). +const MAX_TEXT: usize = 65_536; + +/// An error unless `n`, the length a string or ID declares, is at most [`MAX_TEXT`]. +fn text_len(n: usize) -> Result { + if n > MAX_TEXT { + return Err(format!("a text in the slices has more than the {MAX_TEXT} characters read")); + } + Ok(n) +} + +/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped. +fn unicode(r: &mut Reader<'_>) -> Result { + let n = text_len(r.u32()? as usize)?; + let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?; + let units: Vec = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect(); + Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string()) +} + +/// A descriptor's value, as far as the slices need it. +#[derive(Clone, Debug, PartialEq)] +enum Value { + Long(i32), + Double(f64), + Bool(bool), + Text(String), + /// An enumeration's type and value. + Enum(String, String), + Object(Vec<(String, Value)>), + List(Vec), + /// A value of another type, read past. + Other, +} + +/// The value with key `key`. +fn field<'a>(d: &'a [(String, Value)], key: &str) -> Option<&'a Value> { + d.iter().find(|(k, _)| k == key).map(|(_, v)| v) +} + +/// A whole number: a long, or a finite double rounded. +fn number(v: Option<&Value>) -> Option { + match v? { + Value::Long(n) => Some(i64::from(*n)), + Value::Double(d) if d.is_finite() && d.abs() < 1e12 => Some(d.round() as i64), + _ => None, + } +} + +/// A key or class ID: a length, then that many characters, or four when the length is 0. +fn id(r: &mut Reader<'_>) -> Result { + let n = text_len(r.u32()? as usize)?; + let b = r.take(if n == 0 { 4 } else { n })?; + Ok(String::from_utf8_lossy(b).into_owned()) +} + +/// A class: its Unicode name, then its ID. +fn class(r: &mut Reader<'_>) -> Result<(), String> { + unicode(r)?; + id(r)?; + Ok(()) +} + +/// A descriptor: its class, the count of its items, then each item's key, type and value. +fn descriptor(r: &mut Reader<'_>, depth: usize, budget: &mut usize) -> Result, String> { + if depth > MAX_DEPTH { + return Err("the slices' descriptor nests too deep".into()); + } + class(r)?; + let count = r.u32()? as usize; + let mut out = vec![]; + for _ in 0..count { + let key = id(r)?; + let kind = r.array::<4>()?; + out.push((key, value(r, &kind, depth, budget)?)); + } + Ok(out) +} + +/// A value of type `kind`. +fn value(r: &mut Reader<'_>, kind: &[u8; 4], depth: usize, budget: &mut usize) -> Result { + *budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?; + Ok(match kind { + b"long" => Value::Long(r.u32()? as i32), + b"doub" => Value::Double(f64::from_be_bytes(r.array()?)), + b"UntF" => { + r.take(4)?; + Value::Double(f64::from_be_bytes(r.array()?)) + } + b"UnFl" => { + r.take(4)?; + Value::Double(f64::from(f32::from_be_bytes(r.array()?))) + } + b"bool" => Value::Bool(r.u8()? != 0), + b"TEXT" => Value::Text(unicode(r)?), + b"enum" => Value::Enum(id(r)?, id(r)?), + b"Objc" | b"GlbO" => Value::Object(descriptor(r, depth + 1, budget)?), + b"VlLs" => { + if depth >= MAX_DEPTH { + return Err("the slices' descriptor nests too deep".into()); + } + let count = r.u32()? as usize; + let mut items = vec![]; + for _ in 0..count { + let kind = r.array::<4>()?; + items.push(value(r, &kind, depth + 1, budget)?); + } + Value::List(items) + } + b"comp" => { + r.take(8)?; + Value::Other + } + b"type" | b"GlbC" => { + class(r)?; + Value::Other + } + b"tdta" | b"alis" => { + let n = r.u32()? as usize; + r.take(n)?; + Value::Other + } + b"obj " => { + let count = r.u32()? as usize; + for _ in 0..count { + *budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?; + match &r.array::<4>()? { + b"prop" => { + class(r)?; + id(r)?; + } + b"Clss" => class(r)?, + b"Enmr" => { + class(r)?; + id(r)?; + id(r)?; + } + b"rele" => { + class(r)?; + r.take(4)?; + } + b"Idnt" | b"indx" => { + r.take(4)?; + } + b"name" => { + class(r)?; + unicode(r)?; + } + k => return Err(format!("the slices' descriptor has a reference of an unknown kind ({})", String::from_utf8_lossy(k))), + } + } + Value::Other + } + k => return Err(format!("the slices' descriptor has a value of an unknown type ({})", String::from_utf8_lossy(k))), + }) +} + +/// The slices of PSD or PSB file `bytes` laid over `canvas`, the box its canvas takes (points), +/// each clipped to the canvas, with warnings: for slices that lie wholly outside it or have no +/// size, and for slices that can't be read (the file comes in without them). Empty, without a +/// warning, when the file stores no slices. +pub(crate) fn over(bytes: &[u8], canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec) { + match read(bytes) { + Ok(None) => (vec![], vec![]), + Ok(Some(s)) => laid_over(&s.slices, s.size, canvas), + Err(e) => (vec![], vec![format!("the slices can't be read ({e}) and were left out")]), + } +} + +/// `slices` of a canvas of `size` pixels laid over `canvas` (points). +fn laid_over(slices: &[PsdSlice], (w, h): (u32, u32), canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec) { + let (sx, sy) = (canvas.width() / f64::from(w.max(1)), canvas.height() / f64::from(h.max(1))); + let mut out = vec![]; + for s in slices { + let [l, t, r, b] = s.rect; + let (l, r) = (l.clamp(0, i64::from(w)), r.clamp(0, i64::from(w))); + let (t, b) = (t.clamp(0, i64::from(h)), b.clamp(0, i64::from(h))); + if l < r && t < b { + let x = |v: i64| canvas.x0 + v as f64 * sx; + let y = |v: i64| canvas.y0 + v as f64 * sy; + out.push((Rect::new(x(l), y(t), x(r), y(b)), s.options.clone())); + } + } + let warnings = match slices.len() - out.len() { + 0 => vec![], + 1 => vec!["1 slice lies outside the canvas or has no size and was left out".to_string()], + n => vec![format!("{n} slices lie outside the canvas or have no size and were left out")], + }; + (out, warnings) +} + +/// How many slices of PSD or PSB file `bytes` come in (`document.psdInfo`): 0 when it stores none +/// or they can't be read. +pub(crate) fn count(bytes: &[u8]) -> usize { + match read(bytes) { + Ok(Some(Stored { slices, size: (w, h) })) => laid_over(&slices, (w, h), Rect::new(0.0, 0.0, f64::from(w), f64::from(h))).0.len(), + _ => 0, + } +} diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 31f670d7ff..298f3d22dc 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1,7 +1,8 @@ //! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and //! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers //! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export -//! read back, and damaged files read without a panic. +//! read back, and damaged files read without a panic. Placing them with their layers as objects +//! (`file.place`'s `layers` and `hiddenLayers`), and `document.psdInfo`. use serde_json::{Value, json}; use vectorcraft_color::BlendMode; @@ -967,10 +968,12 @@ fn damaged_layers_never_panic() { let mut f = good.clone(); f[i] = v; let _ = psdlayers::import(&f, true, 1 << 30, cms); + let _ = psdlayers::info(&f); } } for n in 0..good.len() { let _ = psdlayers::import(&good[..n], true, 1 << 30, cms); + let _ = psdlayers::info(&good[..n]); } // A layer past the memory allowed is refused, not read. assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large")); @@ -1015,3 +1018,186 @@ fn merges_keep_pass_through_groups_blending_with_what_is_below() { assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}"); } } + +/// `file.place` of `f` with `p` into a new 100 × 100 pt document, centred on (50, 50). +fn place(f: &[u8], p: Value) -> (Session, crate::cmd::Result) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f), "at": [50, 50]}), p)); + (s, r) +} + +/// The one object `file.place` placed. +fn placed(s: &Session, r: &Value) -> Node { + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +#[test] +fn placing_with_layers_embeds_the_layers_as_one_group() { + let f = file(8, 8, &stack(), 8, false, false); + let (mut s, r) = place(&f, json!({"layers": true})); + let r = r.unwrap(); + assert_eq!((&r["format"], &r["linked"], &r["warnings"]), (&json!("psd"), &json!(false), &json!([HIDDEN_1])), "{r}"); + let g = placed(&s, &r); + assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "one group, unclipped: its layers lie on the canvas"); + assert_eq!(name(&g), "layers.psd"); + let kids = g.children().unwrap(); + assert_eq!(kids.iter().map(|c| name(c)).collect::>(), ["Bottom", "Folder", "Screens", "Faded"], "bottom first"); + // A layer is its image, where the merged image would put it: the 8 pt canvas centred on (50, 50). + let ((x, y), px) = pixels_of(&s, &kids[0]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((46.0, 46.0), (8, 8), [255, 0, 0, 255])); + // A group is a group of its layers; a pass-through group isn't isolated, another mode's is. + let folder = &kids[1]; + assert!(matches!(folder.kind, NodeKind::Group { .. }) && !folder.isolate && folder.blend == BlendMode::Normal); + let inner = folder.children().unwrap(); + assert_eq!(inner.iter().map(|c| name(c)).collect::>(), ["Inner A"], "the hidden layer is left out"); + assert!(matches!(inner[0].kind, NodeKind::Image(_)) && inner[0].blend == BlendMode::Multiply && (inner[0].opacity - 128.0 / 255.0).abs() < 1e-6); + let screens = &kids[2]; + assert!(screens.isolate && screens.blend == BlendMode::Screen); + let ((x, y), px) = pixels_of(&s, &screens.children().unwrap()[0]); + assert_eq!(((x, y), px.get_pixel(0, 0).0), ((48.0, 48.0), [10, 20, 30, 128])); + assert!((kids[3].opacity - 102.0 / 255.0).abs() < 1e-6, "fill opacity: {}", kids[3].opacity); + // One undo step. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty))); + // Hidden layers come in hidden when asked for. + let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true})); + let r = r.unwrap(); + assert_eq!(r["warnings"], json!([]), "{r}"); + let g = placed(&s, &r); + let inner: Vec<(&str, bool)> = g.children().unwrap()[1].children().unwrap().iter().map(|c| (name(c), c.visible)).collect(); + assert_eq!(inner, [("Inner A", true), ("Inner B", false)]); + // Without `layers`, the merged image, in the same box. + let (s, r) = place(&f, json!({})); + let r = r.unwrap(); + let flat = placed(&s, &r); + let ((x, y), px) = pixels_of(&s, &flat); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((46.0, 46.0), (8, 8), [128, 128, 128, 255]), "{r}"); +} + +#[test] +fn placed_layers_keep_their_masks_and_are_clipped_to_the_canvas() { + let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]); + masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255])); + let (s, r) = place(&file(8, 8, &[masked], 8, false, false), json!({"layers": true})); + let g = placed(&s, &r.unwrap()); + let kids = g.children().unwrap(); + assert!(matches!(kids[0].kind, NodeKind::Image(_)), "the layer is its image"); + let m = kids[0].extras().mask.as_deref().expect("the layer mask as the image's opacity mask"); + let ((x, y), px) = pixels_of(&s, &m.art); + assert_eq!(((x, y), px.dimensions(), m.clip), ((48.0, 48.0), (2, 2), true), "the mask moves with its layer"); + // A layer that reaches past the canvas: the group is clipped to the canvas, as the merged + // image shows only the canvas. + let over = layer("Over", [-2, -2, 6, 6], [0, 255, 0, 255]); + let (s, r) = place(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), over], 8, false, false), json!({"layers": true})); + let r = r.unwrap(); + let g = placed(&s, &r); + assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}"); + let kids = g.children().unwrap(); + let b = kids[0].geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap(); + assert!(matches!(kids[0].kind, NodeKind::Path { clipping: true, .. })); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (46.0, 46.0, 54.0, 54.0), "the clipping path is the canvas"); + assert_eq!(kids[1..].iter().map(|c| name(c)).collect::>(), ["Bottom", "Over"]); + assert_eq!(pixels_of(&s, &kids[2]).0, (44.0, 44.0)); + // A hidden layer that reaches past the canvas clips the group too, so showing it later draws + // only the canvas. Left out, it doesn't. + let mut hidden = layer("Hidden", [-2, -2, 6, 6], [0, 255, 0, 255]); + hidden.hidden = true; + let f = file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), hidden], 8, false, false); + let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true})); + let r = r.unwrap(); + let g = placed(&s, &r); + assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}"); + assert_eq!(g.children().unwrap()[1..].iter().map(|c| (name(c), c.visible)).collect::>(), [("Bottom", true), ("Hidden", false)]); + let (s, r) = place(&f, json!({"layers": true})); + assert!(matches!(placed(&s, &r.unwrap()).kind, NodeKind::Group { clip: false, .. })); +} + +#[test] +fn placing_with_layers_never_links_and_refuses_values_it_cant_use() { + let f = file(8, 8, &stack(), 8, false, false); + let dir = std::env::temp_dir().join(format!("vc-psd-place-layers-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("layers.psd"); + std::fs::write(&path, &f).unwrap(); + let from_path = |p: Value| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &merge(json!({"path": path.to_str().unwrap()}), p)); + (s, r) + }; + // From a path, `layers` embeds: `link` is then false unless given, and `link: true` is refused. + let (s, r) = from_path(json!({"layers": true})); + let r = r.unwrap(); + assert_eq!(r["linked"], json!(false), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Group { .. })); + let (s, r) = from_path(json!({"layers": true, "link": true})); + assert!(r.unwrap_err().to_string().contains("a linked PSD file is placed as its flat image")); + assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "nothing is placed"); + // Without `layers` the file is linked as before. + let (s, r) = from_path(json!({})); + let r = r.unwrap(); + assert_eq!(r["linked"], json!(true), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_))); + // A file without layers is embedded as its merged image, without a warning. + let flat = { + let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false); + let at = 26 + 8; + let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize; + f.splice(at..at + 4 + len, 0u32.to_be_bytes()); + f + }; + std::fs::write(&path, &flat).unwrap(); + let (s, r) = from_path(json!({"layers": true})); + let r = r.unwrap(); + assert_eq!((&r["linked"], &r["warnings"]), (&json!(false), &json!([])), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_))); + // Layers that are all left out: the merged image, with the importer's warnings. + let mut gone = layer("Gone", [0, 0, 2, 2], [9, 9, 9, 255]); + gone.hidden = true; + let (s, r) = place(&file(2, 2, &[gone], 8, false, false), json!({"layers": true})); + let r = r.unwrap(); + assert_eq!((&r["linked"], r["warnings"].as_array().map(Vec::len)), (&json!(false), Some(1)), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_))); + // Layers that can't be read: the merged image, with a warning. + let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false); + let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap(); + cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes()); + let (s, r) = place(&cut, json!({"layers": true})); + let r = r.unwrap(); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_))); + // Values the command can't use are errors, and nothing is placed. + for (p, why) in [ + (json!({"hiddenLayers": true}), "hiddenLayers applies to a PSD file placed with layers: true"), + (json!({"layers": true, "link": true}), "a linked PSD file is placed as its flat image"), + (json!({"layers": "yes"}), "layers must be true or false"), + (json!({"layers": true, "hiddenLayers": 1}), "hiddenLayers must be true or false"), + ] { + let (s, r) = place(&f, p.clone()); + assert!(r.unwrap_err().to_string().contains(why), "{p}"); + assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{p}"); + } + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let q = s.execute("file.place.queue", &json!({"paths": [path.to_str().unwrap()], "layers": "yes"})); + assert!(q.unwrap_err().to_string().contains("`layers` must be true or false")); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn psd_info_counts_the_layers_without_opening_the_file() { + let mut s = Session::new(); + let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": vectorcraft_format::base64_encode(f)})); + let r = info(&mut s, &file(8, 8, &stack(), 8, false, false)).unwrap(); + assert_eq!(r, json!({"format": "psd", "width": 8, "height": 8, "layers": 5, "hiddenLayers": 1, "groups": 2, "slices": 0})); + let r = info(&mut s, &file(4, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 16, true, true)).unwrap(); + assert_eq!((&r["format"], &r["width"], &r["height"], &r["layers"]), (&json!("psb"), &json!(4), &json!(2), &json!(1)), "{r}"); + // Layer records that can't be read count as no layers: the file opens as its merged image. + let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false); + let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap(); + cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes()); + assert_eq!(info(&mut s, &cut).unwrap()["layers"], json!(0)); + assert!(info(&mut s, b"not a psd").unwrap_err().to_string().contains("not a PSD file")); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs new file mode 100644 index 0000000000..42dc33c600 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -0,0 +1,459 @@ +//! A PSD or PSB file's slices (image resource 1050) opened and placed as user slices +//! (`document.open`'s and `file.place`'s `importSlices`): version 6 records and version 7 and 8 +//! descriptors, built from the Photoshop File Formats Specification's "Slices resource format"; +//! their options, slices outside the canvas, damaged or unknown slice data, placing scaled and +//! moved in one undo step, linked files, and `document.psdInfo`'s count. + +use serde_json::{Value, json}; +use vectorcraft_doc::{SliceKind, SliceOptions}; +use vectorcraft_geom::Rect; + +use crate::Session; + +/// A Unicode string: a count of UTF-16 units, then the units. +fn ustr(s: &str) -> Vec { + let units: Vec = s.encode_utf16().collect(); + let mut b = (units.len() as u32).to_be_bytes().to_vec(); + b.extend(units.iter().flat_map(|u| u.to_be_bytes())); + b +} + +/// One version 6 slice record. +#[derive(Clone)] +struct S { + /// 0: generated automatically, 1: follows a layer, 2: made by the user. + origin: u32, + name: &'static str, + /// 0: No Image, 1: Image. + kind: u32, + /// Left, top, right, bottom (px). + rect: [i32; 4], + url: &'static str, + target: &'static str, + message: &'static str, + alt: &'static str, + html: bool, + cell: &'static str, + /// Alpha, red, green, blue. + argb: [u8; 4], +} + +fn user(name: &'static str, rect: [i32; 4]) -> S { + S { origin: 2, name, kind: 1, rect, url: "", target: "", message: "", alt: "", html: false, cell: "", argb: [0; 4] } +} + +/// Resource 1050 in version 6, each record followed by `trailing` (a Photoshop 7 descriptor, or +/// nothing). +fn v6(slices: &[S], trailing: &[u8]) -> Vec { + let mut b = 6u32.to_be_bytes().to_vec(); + b.extend([0u8; 16]); + b.extend(ustr("group")); + b.extend((slices.len() as u32).to_be_bytes()); + for (i, s) in slices.iter().enumerate() { + b.extend((i as u32 + 1).to_be_bytes()); + b.extend(0u32.to_be_bytes()); + b.extend(s.origin.to_be_bytes()); + if s.origin == 1 { + b.extend(7u32.to_be_bytes()); + } + b.extend(ustr(s.name)); + b.extend(s.kind.to_be_bytes()); + for v in s.rect { + b.extend(v.to_be_bytes()); + } + for t in [s.url, s.target, s.message, s.alt] { + b.extend(ustr(t)); + } + b.push(u8::from(s.html)); + b.extend(ustr(s.cell)); + b.extend([0u8; 8]); + b.extend(s.argb); + b.extend(trailing); + } + b +} + +/// A descriptor value. +enum D { + Long(i32), + Doub(f64), + Bool(bool), + Text(&'static str), + Enum(&'static str, &'static str), + Obj(Vec<(&'static str, D)>), + List(Vec), +} + +/// A key or class ID: a four-character one with length 0, else its length and characters. +fn key(k: &str) -> Vec { + let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec(); + b.extend(k.as_bytes()); + b +} + +/// A descriptor: an empty class name, the class ID, the count, then each item. +fn descriptor(items: &[(&str, D)]) -> Vec { + let mut b = ustr(""); + b.extend(key("null")); + b.extend((items.len() as u32).to_be_bytes()); + for (k, v) in items { + b.extend(key(k)); + b.extend(value(v)); + } + b +} + +/// A value's type, then the value. +fn value(v: &D) -> Vec { + let mut b = vec![]; + match v { + D::Long(n) => { + b.extend(b"long"); + b.extend(n.to_be_bytes()); + } + D::Doub(d) => { + b.extend(b"doub"); + b.extend(d.to_be_bytes()); + } + D::Bool(on) => { + b.extend(b"bool"); + b.push(u8::from(*on)); + } + D::Text(t) => { + b.extend(b"TEXT"); + b.extend(ustr(t)); + } + D::Enum(t, e) => { + b.extend(b"enum"); + b.extend(key(t)); + b.extend(key(e)); + } + D::Obj(items) => { + b.extend(b"Objc"); + b.extend(descriptor(items)); + } + D::List(items) => { + b.extend(b"VlLs"); + b.extend((items.len() as u32).to_be_bytes()); + for i in items { + b.extend(value(i)); + } + } + } + b +} + +/// A bounds object: top, left, bottom and right. +fn bounds(l: i32, t: i32, r: i32, b: i32) -> D { + D::Obj(vec![("Top ", D::Long(t)), ("Left", D::Long(l)), ("Btom", D::Long(b)), ("Rght", D::Long(r))]) +} + +/// Resource 1050 in `version` 7 or 8 holding `slices`. +fn v7(version: u32, slices: Vec) -> Vec { + let mut b = version.to_be_bytes().to_vec(); + b.extend(16u32.to_be_bytes()); + b.extend(descriptor(&[("bounds", bounds(0, 0, 20, 20)), ("baseName", D::Text("poster")), ("slices", D::List(slices))])); + b +} + +/// A 20 × 20 px PSD file written by `document.export`, with its layers (two) or flat. +fn psd(layers: bool) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({ "color": "#ff0000" })).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + s.execute("layer.new", &json!({ "name": "Top" })).unwrap(); + s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 10, "height": 10})).unwrap(); + let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +/// `psd` with image resource `id` holding `data` added to its image resources. +fn with_resource(psd: &[u8], id: u16, data: &[u8]) -> Vec { + let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize; + let colors = 26 + 4 + u32_at(26); + let len = u32_at(colors); + let mut block = b"8BIM".to_vec(); + block.extend(id.to_be_bytes()); + block.extend([0, 0]); + block.extend((data.len() as u32).to_be_bytes()); + block.extend(data); + block.resize(block.len().next_multiple_of(2), 0); + let mut out = psd[..colors].to_vec(); + out.extend(((len + block.len()) as u32).to_be_bytes()); + out.extend(&psd[colors + 4..colors + 4 + len]); + out.extend(block); + out.extend(&psd[colors + 4 + len..]); + out +} + +fn b64(f: &[u8]) -> String { + vectorcraft_format::base64_encode(f) +} + +fn open(f: &[u8], extra: Value) -> (Session, Value) { + let mut s = Session::new(); + let mut p = json!({"name": "poster.psd", "dataBase64": b64(f)}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("document.open", &p).unwrap(); + (s, r) +} + +/// The document's user slices: rectangle and options. +fn slices(s: &Session) -> Vec<(Rect, SliceOptions)> { + s.doc().unwrap().doc.slices.iter().map(|x| (x.rect, x.options.clone())).collect() +} + +fn warnings(r: &Value) -> Vec { + r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default() +} + +#[test] +fn version_6_slices_open_as_user_slices_with_their_options() { + let linked = S { origin: 1, url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", ..user("logo", [2, 4, 10, 8]) }; + let plain = S { kind: 0, cell: "a < b & c", argb: [0, 0, 0, 0], ..user("note", [10, 10, 20, 20]) }; + let html = S { kind: 0, html: true, cell: "Hi", argb: [255, 0x12, 0x34, 0x56], ..user("", [0, 12, 6, 18]) }; + let matte = S { argb: [0, 1, 2, 3], cell: "ignored", ..user("matte", [12, 0, 18, 6]) }; + let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) }; + let data = v6(&[linked, plain, html, matte, auto], &[]); + for layers in [true, false] { + let f = with_resource(&psd(layers), 1050, &data); + // Either conversion brings the slices in; the automatic one stays out. + for p in [json!({}), json!({"layers": false})] { + let (s, r) = open(&f, p); + assert!(warnings(&r).is_empty(), "{r}"); + let got = slices(&s); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!(got[0].0, Rect::new(2.0, 4.0, 10.0, 8.0)); + assert_eq!( + got[0].1, + SliceOptions { + kind: SliceKind::Image, + name: "logo".into(), + url: "https://example.com/".into(), + target: "_blank".into(), + message: "Go".into(), + alt: "Logo".into(), + ..Default::default() + } + ); + // Plain cell text is escaped as the HTML a No Image cell shows; HTML stays as it is. + assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.background.as_str()), (SliceKind::NoImage, "a < b & c", "")); + assert_eq!((got[2].1.text.as_str(), got[2].1.background.as_str(), got[2].1.name.as_str()), ("Hi", "#123456", "")); + // An Image slice's cell text isn't kept; a background with no alpha is the matte. + assert_eq!((got[3].1.text.as_str(), got[3].1.background.as_str()), ("", "matte")); + // Web output lays them out with auto slices around them. + let layout = s.doc().unwrap().doc.slice_layout(); + assert_eq!(layout.iter().filter(|a| a.source == vectorcraft_doc::SliceSource::User).count(), 4); + assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto)); + } + } +} + +#[test] +fn photoshop_7_descriptors_after_version_6_records_are_read_past() { + let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat(); + let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5]), user("b", [5, 5, 10, 10])], &trailing)); + let (s, r) = open(&f, json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + let names: Vec = slices(&s).into_iter().map(|(_, o)| o.name).collect(); + assert_eq!(names, ["a", "b"]); +} + +#[test] +fn version_6_descriptors_share_one_budget_of_values() { + // Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold; + // 100 of them hold 250,100 together. + let list = D::List((0..2_500).map(D::Long).collect()); + let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("many", list)])].concat(); + let records: Vec = (0..100).map(|_| user("a", [0, 0, 5, 5])).collect(); + // Alone, one such descriptor is read past. + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records[..1], &trailing)), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!(slices(&s).len(), 1); + // Together they are refused, and the file opens without slices. + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({})); + let w = warnings(&r); + assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("too many values")), "{w:?}"); + assert!(slices(&s).is_empty()); +} + +#[test] +fn version_7_and_8_descriptors_open_as_user_slices() { + let slice = |origin: &'static str, kind: &'static str, l: i32, t: i32, r: i32, b: i32| { + D::Obj(vec![ + ("sliceID", D::Long(1)), + ("groupID", D::Long(0)), + ("origin", D::Enum("ESliceOrigin", origin)), + ("Type", D::Enum("ESliceType", kind)), + ("bounds", bounds(l, t, r, b)), + ("Nm ", D::Text("cell")), + ("url", D::Text("https://example.com/")), + ("null", D::Text("_top")), + ("Msge", D::Text("msg")), + ("altTag", D::Text("alt")), + ("cellTextIsHTML", D::Bool(false)), + ("cellText", D::Text("x>y")), + ("bgColorType", D::Enum("ESliceBGColorType", "Clr ")), + ("bgColor", D::Obj(vec![("Rd ", D::Doub(255.0)), ("Grn ", D::Doub(128.0)), ("Bl ", D::Long(0))])), + ]) + }; + for version in [7, 8] { + let data = v7( + version, + vec![slice("userGenerated", "Img ", 1, 2, 9, 10), slice("autoGenerated", "Img ", 0, 0, 20, 1), slice("layer", "noImage", 10, 10, 15, 15)], + ); + let (s, r) = open(&with_resource(&psd(true), 1050, &data), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + let got = slices(&s); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[0].0, Rect::new(1.0, 2.0, 9.0, 10.0)); + assert_eq!( + got[0].1, + SliceOptions { + name: "cell".into(), + url: "https://example.com/".into(), + target: "_top".into(), + message: "msg".into(), + alt: "alt".into(), + background: "#ff8000".into(), + ..Default::default() + } + ); + assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.url.as_str()), (SliceKind::NoImage, "x>y", "")); + } +} + +#[test] +fn import_slices_false_leaves_them_out_and_must_be_a_switch() { + let f = with_resource(&psd(true), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[])); + let (s, _) = open(&f, json!({"importSlices": false})); + assert!(slices(&s).is_empty()); + let mut s = Session::new(); + let e = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": "yes"})).unwrap_err(); + assert!(e.to_string().contains("importSlices must be true or false"), "{e}"); +} + +#[test] +fn slices_that_cant_be_read_warn_and_the_file_still_opens() { + let good = v6(&[user("a", [0, 0, 5, 5])], &[]); + let mut bad_descriptor = v7(7, vec![]); + bad_descriptor[4..8].copy_from_slice(&15u32.to_be_bytes()); + let cases: Vec<(Vec, &str)> = vec![ + (good[..good.len() - 3].to_vec(), "cut short"), + ([9u32.to_be_bytes().to_vec(), good[4..].to_vec()].concat(), "version 9"), + (bad_descriptor, "version other than 16"), + // The count follows the version, the bounds and the group's name. + ([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"), + (v7(8, vec![D::Long(3)]), "other than a slice"), + // A whole record whose name is longer than a slice's text may be. + (v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"), + ]; + for (data, why) in cases { + for layers in [true, false] { + let (s, r) = open(&with_resource(&psd(layers), 1050, &data), json!({})); + let w = warnings(&r); + assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains(why)), "{why}: {w:?}"); + assert!(slices(&s).is_empty()); + // The art still came in. + assert!(s.doc().unwrap().doc.art_bounds().is_some(), "{why}"); + } + } + // A name of the longest length read comes in. + let longest = v6(&[user("a".repeat(65_536).leak(), [0, 0, 5, 5])], &[]); + let (s, r) = open(&with_resource(&psd(false), 1050, &longest), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!(slices(&s).first().map(|(_, o)| o.name.len()), Some(65_536)); + // A file without slices opens without a word about them. + let (s, r) = open(&psd(true), json!({})); + assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); +} + +#[test] +fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() { + let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]); + let (s, r) = open(&with_resource(&psd(false), 1050, &data), json!({})); + assert_eq!(warnings(&r), ["2 slices lie outside the canvas or have no size and were left out"]); + let got: Vec<(Rect, String)> = slices(&s).into_iter().map(|(r, o)| (r, o.name)).collect(); + assert_eq!(got, [(Rect::new(0.0, 0.0, 5.0, 20.0), "over".to_string()), (Rect::new(1.0, 1.0, 2.0, 2.0), "in".to_string())]); +} + +#[test] +fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() { + let data = v6(&[user("a", [0, 0, 10, 10]), user("b", [10, 10, 20, 20])], &[]); + for layers in [false, true] { + let f = with_resource(&psd(layers), 1050, &data); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + // Fitted into a 40 pt square at (100, 60): twice the size. + let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "rect": [100, 60, 40, 40], "layers": layers})).unwrap(); + assert_eq!(r["slices"].as_array().map(Vec::len), Some(2), "{r}"); + let got: Vec = slices(&s).into_iter().map(|(r, _)| r).collect(); + assert_eq!(got, [Rect::new(100.0, 60.0, 120.0, 80.0), Rect::new(120.0, 80.0, 140.0, 100.0)]); + // The placed art stays selected, and one undo takes the art and the slices away. + assert_eq!(s.doc().unwrap().selection.objects.len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(slices(&s).is_empty()); + assert!(s.doc().unwrap().doc.art_bounds().is_none()); + // Centered on `at` at 100%. + s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "at": [100, 100], "layers": layers})).unwrap(); + assert_eq!(slices(&s)[0].0, Rect::new(90.0, 90.0, 100.0, 100.0)); + // `importSlices: false` places the art alone. + let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": false, "layers": layers})).unwrap(); + assert!(r.get("slices").is_none()); + assert_eq!(slices(&s).len(), 2); + } +} + +#[test] +fn linked_files_are_placed_without_their_slices() { + let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("poster.psd"); + std::fs::write(&path, with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]))).unwrap(); + let path = path.to_string_lossy().into_owned(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + assert_eq!((&r["linked"], r.get("slices")), (&json!(true), None)); + assert!(slices(&s).is_empty()); + let e = s.execute("file.place", &json!({ "path": path, "importSlices": true })).unwrap_err(); + assert!(e.to_string().contains("importSlices: a linked PSD file is placed as its flat image"), "{e}"); + // Embedded from its path, they come in. + let r = s.execute("file.place", &json!({ "path": path, "link": false })).unwrap(); + assert_eq!((&r["linked"], r["slices"].as_array().map(Vec::len)), (&json!(false), Some(1))); + // file.place.info counts what a place would bring in. + let info = s.execute("file.place.info", &json!({ "path": path, "link": false })).unwrap(); + assert_eq!(info["slices"], json!(1)); + let info = s.execute("file.place.info", &json!({ "path": path })).unwrap(); + assert_eq!(info["slices"], json!(0)); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn psd_info_counts_the_slices_that_come_in() { + let mut s = Session::new(); + let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": b64(f)})).unwrap(); + let data = v6(&[user("a", [0, 0, 5, 5]), S { origin: 0, ..user("auto", [5, 5, 20, 20]) }, user("out", [30, 30, 40, 40])], &[]); + assert_eq!(info(&mut s, &with_resource(&psd(false), 1050, &data))["slices"], json!(1)); + assert_eq!(info(&mut s, &with_resource(&psd(true), 1050, &data[..data.len() - 4]))["slices"], json!(0)); + assert_eq!(info(&mut s, &psd(true))["slices"], json!(0)); +} + +#[test] +fn damaged_slices_never_panic() { + let data = v7(8, vec![D::Obj(vec![("origin", D::Enum("ESliceOrigin", "userGenerated")), ("bounds", bounds(0, 0, 5, 5))])]); + let base = with_resource(&psd(false), 1050, &data); + let start = base.windows(data.len()).position(|w| w == data).unwrap(); + for at in (start - 12..start + data.len()).step_by(3) { + for v in [0u8, 0x7f, 0xff] { + let mut f = base.clone(); + f[at] = v; + let mut s = Session::new(); + let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})); + let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})); + } + } +} diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 46231dcd0d..83216b2f43 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -4,6 +4,10 @@ //! - A raster image becomes one image at 100% of its physical size: its pixels at the resolution //! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with //! `link` ([`super::links`]). +//! - A PSD or PSB file placed with `layers` becomes one group of its layers as objects, embedded +//! ([`fileio::psd_layers`]); otherwise it is an image like any other, its merged image. An +//! embedded one brings its slices in as user slices, placed with its art (`importSlices`, +//! [`fileio::psd_slices`]). //! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options //! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`). //! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or @@ -45,7 +49,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SymbolBoxes}; +use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes}; use vectorcraft_geom::{Affine, Point, Rect, shapes}; use vectorcraft_pdf::CropTo; @@ -75,7 +79,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -84,7 +88,7 @@ pub fn specs() -> Vec { "Placed File Info", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", + "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", always, info ), @@ -102,7 +106,7 @@ pub fn specs() -> Vec { "Load Place Cursor", [], None, - "{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}", + "{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}", has_doc, queue ), @@ -148,16 +152,33 @@ struct Loaded { board: Option, } +/// A PSD or PSB file's slices, embedded with `importSlices`: their rectangles over the natural box +/// of its art, and their options. +type Slices = Vec<(Rect, SliceOptions)>; + /// Points per pixel of a raster image at the resolution it declares (72 ppi when none). pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) { let (x, y) = ppi.unwrap_or((72.0, 72.0)); (72.0 / x, 72.0 / y) } +/// [`load_sliced`] without the slices. +fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result { + load_into(p, cmd, board, link_pdf, &mut vec![]) +} + +/// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in. +fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result<(Loaded, Slices)> { + let mut slices = vec![]; + let l = load_into(p, cmd, board, link_pdf, &mut slices)?; + Ok((l, slices)) +} + /// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board` /// (unless the params name their own box). A PDF/.ai page read from a path is placed linked with -/// Link when `link_pdf` (false for the queries, which read it embedded). -fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result { +/// Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB file's slices +/// go to `slices`. +fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_out: &mut Slices) -> Result { let src = fileio::source(p, cmd)?; let name = fileio::file_name(src.name); // An Affinity file is recognised by its signature, whatever its name says. @@ -237,12 +258,52 @@ fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result match psd_groups(doc) { + Some((art, natural)) => { + *slices_out = psd_slices(slices_from, natural, &mut warnings); + return Ok(Loaded { name, format, art, natural, warnings, link: None, board: None }); + } + // No layer has art: the merged image, embedded. + None => unread = warnings, + }, + // No layers: the merged image, embedded. + Ok(None) => {} + Err(e) => unread.push(format!("the layers can't be read ({e}): the file was placed as its merged image")), + } + } + } if format.raster { let img = fileio::raster_image(&src.bytes)?; let (sx, sy) = pt_per_px(img.ppi); let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy); - let link = src.path.map(|path| super::links::link_info(path, &src.bytes)); - let warnings = fileio::size_note(&img.blob.bytes).into_iter().collect(); + let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes)); + let mut warnings: Vec = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect(); + *slices_out = psd_slices(slices_from, natural, &mut warnings); let clip = fileio::psdread::clipping_path(&src.bytes); return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None }); } @@ -303,6 +364,56 @@ fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result Option<(Art, Rect)> { + let canvas = doc.artboards.first()?.rect; + let nodes = psd_objects(&std::mem::take(&mut doc.layers)); + // Hidden layers count too: showing one later must not draw past the canvas. + let symbols = doc.symbol_boxes(); + let reached = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, reach(&symbols, n)))?; + let past = reached.union(canvas) != canvas; + Some((Art::Vector { src: Box::new(doc), nodes, clip: past.then_some(canvas) }, canvas)) +} + +/// The slices of the PSD or PSB file `bytes` (none without it) laid over `canvas`, the natural box +/// of its art; their warnings go to `warnings`. +fn psd_slices(bytes: Option<&[u8]>, canvas: Rect, warnings: &mut Vec) -> Slices { + let Some(bytes) = bytes else { return vec![] }; + let (slices, notes) = fileio::psd_slices(bytes, canvas); + warnings.extend(notes); + slices +} + +/// The bounds of `n` and every object inside it, hidden ones included. +fn reach(symbols: &SymbolBoxes, n: &Node) -> Option { + match n.children() { + Some(kids) => kids.iter().fold(None, |acc, k| vectorcraft_geom::union_opt(acc, reach(symbols, k))), + None => n.geometric_bounds_with(symbols), + } +} + +/// The layers a PSD import made as objects: a layer of sublayers as a group of them, and a layer +/// holding one image as that image, each with the layer's name, visibility, opacity, blend mode, +/// isolation and opacity mask. +fn psd_objects(layers: &[Arc]) -> Vec { + layers + .iter() + .map(|l| { + let mut n = (**l).clone(); + let NodeKind::Layer { children, .. } = &l.kind else { return n }; + n.kind = match &children[..] { + [c] if matches!(c.kind, NodeKind::Image(_)) => c.kind.clone(), + _ => NodeKind::Group { children: psd_objects(children).into_iter().map(Arc::new).collect(), clip: false }, + }; + n + }) + .collect() +} + /// Page `page` (1-based) of the PDF/.ai/.ait file `src` (`bytes`, read from `path` when there is /// one) as art to place: clipped to the box `opts.crop` names, or (`bounding`) the bounds of its /// art; read with `opts.password`. Only the page placed is read. A .ai saved without PDF @@ -548,6 +659,7 @@ pub struct PlaceJob { pub struct PlaceRead { job: PlaceJob, loaded: Loaded, + slices: Slices, } impl PlaceJob { @@ -562,7 +674,7 @@ impl PlaceJob { /// the renderers' image store for the first frame that draws them /// ([`super::links::readable_and_kept`]). pub fn read(self) -> Result { - let mut loaded = load(&self.params, PLACE, self.target, true)?; + let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?; let linked = loaded.link.is_some() && bool_or(&self.params, "link", true); match &mut loaded.art { Art::Image(img, _) => { @@ -572,7 +684,7 @@ impl PlaceJob { Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?, _ => {} } - Ok(PlaceRead { job: self, loaded }) + Ok(PlaceRead { job: self, loaded, slices }) } } @@ -653,7 +765,7 @@ fn prepare(s: &Session, p: &Value) -> Result { /// Place the file `read` holds in the active document. fn apply(s: &mut Session, read: PlaceRead) -> Result { - let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded } = read; + let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read; let p = ¶ms; let template = bool_or(p, "template", false); let at = at_param(p)?; @@ -699,7 +811,22 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { if let Art::Dcs(a) = &loaded.art { warnings.extend(dcs::swatch_notes(&st.doc, &a.spots)); } - let (id, size) = s.edit("Place", |d, sel| { + // A PSD file's slices move and scale with its art; one that would leave the canvas is left out. + let read_count = read_slices.len(); + let slices: Slices = read_slices + .into_iter() + .filter_map(|(r, o)| { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c); + let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c)); + super::slices::slice_rect_ok(placed).then_some((placed, o)) + }) + .collect(); + match read_count - slices.len() { + 0 => {} + 1 => warnings.push("1 slice would lie outside the canvas and was left out".into()), + n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")), + } + let (id, size, slice_ids) = s.edit("Place", |d, sel| { let node = transformed(build(d, loaded, link), m); let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default(); let (into, index) = match old { @@ -712,15 +839,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { None => (parent, usize::MAX), }; let id = d.insert(into, index, node)?; + let slice_ids: Vec = slices.into_iter().map(|(r, o)| super::slices::add_slice(d, r, o).0).collect(); // Template art is locked: nothing to select. if template { sel.clear() } else { sel.set([id]) } - Ok((id, size)) + Ok((id, size, slice_ids)) })?; let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings }); + if !slice_ids.is_empty() { + out["slices"] = json!(slice_ids); + } // A DCS, PSD or PSB file clipped by its clipping path: its image, which the Links commands // take. if file_clipped { @@ -824,7 +955,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { let thumbnail = p.get("thumbnail").and_then(Value::as_f64); let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]); for mut q in queued { - for k in ["link", "template", "page", "crop", "text", "dxf"] { + for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] { if let Some(v) = p.get(k) { q[k] = v.clone(); } @@ -870,7 +1001,7 @@ impl Session { /// desktop the Place dialog's OK with several files does this off the UI thread). pub fn prepare_place_queue(&self, params: &Value) -> Result { has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?; - check_switches(params, &["link", "template"], QUEUE)?; + check_switches(params, &["link", "template", "layers", "hiddenLayers", "importSlices"], QUEUE)?; check_numbers(params, &["thumbnail"], QUEUE)?; let files = queued_files(params)?; Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files }) @@ -948,7 +1079,7 @@ pub fn read_info(p: &Value) -> Result { check_switches(p, &["link"], "file.place.info")?; check_numbers(p, &["thumbnail"], "file.place.info")?; // A PDF/.ai page linked or not has the same size and art. - let mut l = load(p, "file.place.info", None, false)?; + let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?; let natural = l.natural; let mut out = json!({ "name": l.name, @@ -957,6 +1088,9 @@ pub fn read_info(p: &Value) -> Result { "height": natural.height(), "warnings": std::mem::take(&mut l.warnings), }); + if matches!(l.format.id, "psd" | "psb") { + out["slices"] = json!(slices.len()); + } if let Art::Image(img, _) = &l.art { let (x, y) = img.ppi.unwrap_or((72.0, 72.0)); out["pixelWidth"] = json!(img.width); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 15702244dc..8de519fa4e 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1841,6 +1841,7 @@ proptest! { /// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden /// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count. /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.) + /// Neither does `document.psdInfo`, nor placing them with their layers as objects. #[test] fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::()), 0..12)) { let (name, mut bytes) = raster_samples().swap_remove(which); @@ -1855,6 +1856,10 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "hiddenLayers": true}); let _ = no_panic(s.execute("document.open", &p)); + let _ = no_panic(s.execute("document.psdInfo", &p)); + let _ = no_panic(s.execute("file.new", &json!({}))); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "layers": true, "hiddenLayers": true}); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err()); } diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 18b67e6c6f..c1e1d664df 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -1038,7 +1038,8 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() { /// The documents [`the_writer_counts_objects_as_the_reader_reads_them`] writes: groups, compound /// paths, guides, sublayers, clipping groups and layers, painted clipping paths, opacity masks, /// gradients, pattern definitions and tiles, images, type, symbol definitions and instances, -/// objects with art styles, objects bound to variables and live envelopes. +/// objects with art styles, objects bound to variables, live envelopes, and the rectangles of the +/// bounds of wrapped objects written as their art. fn counted() -> Vec<(&'static str, Document)> { vec![ ("sample", sample()), @@ -1054,9 +1055,28 @@ fn counted() -> Vec<(&'static str, Document)> { ("blend", blend_doc()), ("brushes", brushes_document()), ("envelopes", envelopes_document()), + ("wrap bounds", wrap_bounds_doc()), ] } +/// Area type below a wrapped symbol instance written as its art and wrapped type written as its +/// outlines, each with the rectangle of its bounds. +fn wrap_bounds_doc() -> Document { + let mut doc = over_area_type(|doc| { + two_leaves(doc); + let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])); + n.isolate = true; + wrapped(n, 4.5, false) + }); + let mut label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Ill", style(60.0, Color::BLACK)); + // Mirrored, so written as its outlines. + label.xf = Affine::new([-1.0, 0.0, 0.0, 1.0, 150.0, 120.0]); + let label = wrapped(text_node(&mut doc, label), -2.0, true); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, label).unwrap(); + doc +} + /// A blend of two squares 20 pt apart with a step every 10 pt, written as its steps. fn blend_doc() -> Document { let mut doc = Document::new(200.0, 100.0); @@ -4088,20 +4108,21 @@ fn predefined_mojikumi_sets_are_reported_as_left_out() { } } -/// The text document has no Bunri-Kinshi: a paragraph with it on and an inseparable pair in it is -/// reported as left out, and comes back off; with it off, or with no pair, nothing is reported. +/// Bunri-Kinshi comes back on or off, with or without an inseparable pair in the paragraph, and +/// nothing is reported. #[test] -fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() { +fn bunri_kinshi_comes_back_with_or_without_a_pair() { use vectorcraft_doc::TextObject; - for (text, on, reported) in [ - ("Wait——now", true, true), - ("Wait——now", false, false), - ("Wait—now", true, false), - ("Wait……now", true, true), - ("Wait‥‥now", true, true), - ("あ〳〵い", true, true), - ("あ〴〵い", true, true), - ("あ〵〳い", true, false), + for (text, on) in [ + ("Wait——now", true), + ("Wait——now", false), + ("Wait—now", true), + ("Wait……now", true), + ("Wait‥‥now", true), + ("あ〳〵い", true), + ("あ〴〵い", true), + ("あ〵〳い", true), + ("あ〵〳い", false), ] { let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), text, style(14.0, Color::BLACK)); t.para.bunri_kinshi = on; @@ -4110,7 +4131,7 @@ fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() { let n = text_node(&mut doc, t); doc.insert(Some(layer), usize::MAX, n).unwrap(); let out = export_ai_editing(&doc, &opts()).unwrap(); - assert_eq!(!out.warnings.is_empty(), reported, "{text} {on}: {:?}", out.warnings); + assert!(out.warnings.is_empty(), "{text} {on}: {:?}", out.warnings); let mut all = vec![]; paths(&read_back(&doc).layers, &mut all); let paras: Vec = all @@ -4120,10 +4141,87 @@ fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() { _ => None, }) .collect(); - assert_eq!(paras, [false], "{text} {on}"); + assert_eq!(paras, [on], "{text} {on}"); } } +/// Each paragraph's Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi come back, and +/// nothing is reported: every value of each, mixed across the paragraphs of one object, Burasagari +/// and Bunri-Kinshi kept under Kinsoku None. The text document lists the Hard and Soft sets, and +/// every paragraph, the normal paragraph style and the document's defaults write all four keys. +/// Another attribute the text document leaves out is still reported. +#[test] +fn kinsoku_settings_come_back_on_each_paragraph() { + use vectorcraft_doc::{Burasagari, Kinsoku, KinsokuShoriType, ParaStyle, TextObject}; + let cases = [ + (Kinsoku::None, KinsokuShoriType::PushInFirst, Burasagari::Forced, true), + (Kinsoku::Soft, KinsokuShoriType::PushOutFirst, Burasagari::Standard, false), + (Kinsoku::Hard, KinsokuShoriType::PushOutOnly, Burasagari::None, true), + (Kinsoku::Hard, KinsokuShoriType::PushInFirst, Burasagari::Standard, false), + (Kinsoku::Soft, KinsokuShoriType::PushOutOnly, Burasagari::Forced, true), + ]; + let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "かな。\n「かな」、\nあ——い\nかな\nかな。", style(14.0, Color::BLACK)); + t.set_paragraph_styles( + cases + .iter() + .map(|&(kinsoku, kinsoku_type, burasagari, bunri_kinshi)| ParaStyle { + kinsoku, + kinsoku_type, + burasagari, + bunri_kinshi, + ..ParaStyle::default() + }) + .collect(), + ); + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&type_lines(&back), &type_lines(&doc)); + let mut all = vec![]; + paths(&back.layers, &mut all); + let read: Vec<_> = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => { + Some(t.paragraph_styles().iter().map(|p| (p.kinsoku, p.kinsoku_type, p.burasagari, p.bunri_kinshi)).collect::>()) + } + _ => None, + }) + .collect(); + assert_eq!(read, [cases.to_vec()]); + let decoded = text_document(&program(&doc)); + let hard = decoded.find("PhotoshopKinsokuHard").unwrap_or_else(|| panic!("{decoded}")); + let soft = decoded.find("PhotoshopKinsokuSoft").unwrap_or_else(|| panic!("{decoded}")); + assert!(hard < soft, "{decoded}"); + // Five paragraphs, then the normal paragraph style and the document's defaults (Hard, Push Out + // Only, no Burasagari, Bunri-Kinshi off). + for (key, count) in [ + ("/27 /nil", 1), + ("/27 0", 4), + ("/27 1", 2), + ("/25 0", 2), + ("/25 1", 1), + ("/25 2", 4), + ("/24 0", 3), + ("/24 1", 2), + ("/24 2", 2), + ("/23 true", 3), + ("/23 false", 4), + ] { + assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}"); + } + let mut lossy = doc.clone(); + let id = lossy.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = lossy.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.underline = true; + } + assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); +} + #[test] fn type_is_written_again_as_the_same_bytes() { let doc = typed(); @@ -11374,6 +11472,42 @@ fn text_wrap_options_of_type_and_envelopes_are_read_back() { same_wraps(&wraps(top), &[(Some("Bent".into()), 2.5, true)]); } +/// The wrap shapes that `doc`'s first area type on its first layer takes from the objects above it, +/// in the type's own space: the bounds of each one's subpaths, and its options. +fn area_wrap_region(doc: &Document) -> Vec<(Vec<[f64; 4]>, f64, bool)> { + use vectorcraft_doc::TextKind; + let mut doc = doc.clone(); + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + let top = doc.layers[0].children().unwrap(); + let Some(NodeKind::Text(t)) = top.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(t) if matches!(t.kind, TextKind::Area { .. }))) + else { + panic!("no area type"); + }; + t.wrap + .iter() + .map(|s| { + let parts = s + .path + .subpaths + .iter() + .map(|sp| { + let b = PathData::new(vec![sp.clone()]).bounds().unwrap_or_default(); + [b.x0, b.y0, b.x1, b.y1] + }) + .collect(); + (parts, s.wrap.offset, s.wrap.invert) + }) + .collect() +} + +/// `before` and `after` hold as many wrap shapes, each with as many subpaths, with bounds within +/// `1e-3`, and the same options. +fn same_region(before: &[(Vec<[f64; 4]>, f64, bool)], after: &[(Vec<[f64; 4]>, f64, bool)]) -> bool { + let close = + |b: &[[f64; 4]], a: &[[f64; 4]]| b.len() == a.len() && b.iter().zip(a).all(|(b, a)| b.iter().zip(a).all(|(x, y)| (x - y).abs() < 1e-3)); + before.len() == after.len() && before.iter().zip(after).all(|(b, a)| close(&b.0, &a.0) && (b.1 - a.1).abs() < 1e-6 && b.2 == a.2) +} + /// Type written as its outlines wraps area type below it by its bounds, as it did before saving, /// not by its glyphs: its text wrap options go on an unpainted rectangle of its bounds, the last /// member of the outlines' group, which keeps the type's name and has no options of its own. @@ -11464,6 +11598,276 @@ fn type_written_as_outlines_keeps_wrapping_by_its_bounds() { assert_eq!(top[1].name.as_deref(), Some("Label"), "{text_out}"); } +/// A 300 × 200 document of area type "Body" filling the page, with `top` above it. +fn over_area_type(make: impl FnOnce(&mut Document) -> Node) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let mut body = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK)); + body.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve", style(10.0, Color::BLACK))]; + body.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 290.0, 190.0)) }; + body.xf = Affine::IDENTITY; + let body = named(text_node(&mut doc, body), "Body"); + let top = make(&mut doc); + for n in [body, top] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} + +/// Symbol "Leaf": two squares in opposite corners of the 20 × 20 square around the origin, apart. +fn two_leaves(doc: &mut Document) { + let a = square(doc, Rect::new(-10.0, -10.0, -6.0, -6.0), LEAF); + let b = square(doc, Rect::new(6.0, 6.0, 10.0, 10.0), LEAF); + let art = group(doc, vec![a, b], false); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); +} + +/// A symbol instance written as its art (its isolation is a group's), a blend and an intertwine, +/// each written as a group of its art, wrap area type below them by their bounds after reopening, +/// as they did before saving, not by the members of that art: the text wrap options go on an +/// unpainted rectangle of the bounds, the group's first member, and the group, which keeps the +/// object's name, isolation, lock and visibility, has none. A positive offset, a negative offset +/// with Invert Wrap, and hidden and locked. +#[test] +fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() { + let instance_of = |offset: f64, invert: bool, visible: bool, locked: bool| { + move |doc: &mut Document| { + two_leaves(doc); + let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])); + n.isolate = true; + (n.visible, n.locked) = (visible, locked); + wrapped(named(n, "Thing"), offset, invert) + } + }; + let blend = |doc: &mut Document| { + let keys = vec![ + Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), + Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false) + }; + let intertwine = |doc: &mut Document| { + let a = Arc::new(square(doc, Rect::new(60.0, 60.0, 80.0, 80.0), Color::gray(0.5))); + let b = Arc::new(square(doc, Rect::new(200.0, 120.0, 220.0, 140.0), Color::gray(0.5))); + wrapped(named(Node::new(doc.alloc_id(), NodeKind::Intertwine { children: vec![a, b] }), "Thing"), 2.0, true) + }; + let repeat = |doc: &mut Document| { + let a = Arc::new(square(doc, Rect::new(100.0, 80.0, 110.0, 90.0), Color::gray(0.5))); + let spec = vectorcraft_doc::RepeatSpec::grid(vec![a], 8.0, 12.0); + wrapped(named(Node::new(doc.alloc_id(), NodeKind::Repeat(spec)), "Thing"), 1.5, false) + }; + // A Fidelity that isn't a whole number: written as its distorted art. + let envelope = |doc: &mut Document| { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + wrapped(named(envelope_node(doc, kind, 50.5, false, EnvelopeOptions::NEW), "Thing"), -3.0, true) + }; + let docs = [ + ("instance", over_area_type(instance_of(4.5, false, true, false)), 4.5, false, true, false), + ("instance, inverted", over_area_type(instance_of(-2.0, true, true, false)), -2.0, true, true, false), + ("instance, hidden and locked", over_area_type(instance_of(3.0, false, false, true)), 3.0, false, false, true), + ("blend", over_area_type(blend), 4.5, false, true, false), + ("intertwine", over_area_type(intertwine), 2.0, true, true, false), + ("repeat", over_area_type(repeat), 1.5, false, true, false), + ("envelope", over_area_type(envelope), -3.0, true, true, false), + ]; + for (name, doc, offset, invert, visible, locked) in docs { + let thing = &doc.layers[0].children().unwrap()[1]; + let want = thing.geometric_bounds().unwrap(); + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), usize::from(visible), "{name}"); + assert!(same_region(&before, &after), "{name}\n{before:?}\n{after:?}\n{text_out}"); + assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{name}: {text_out}"); + let top = back.layers[0].children().unwrap(); + same_wraps(&wraps(top), &[(None, offset, invert)]); + let g = &top[1]; + assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{name}: {text_out}"); + assert_eq!( + (g.name.as_deref(), g.extras().wrap, g.visible, g.locked, g.isolate), + (Some("Thing"), None, visible, locked, thing.isolate), + "{name}" + ); + let first = &g.children().unwrap()[0]; + assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{name}: {text_out}"); + assert_eq!((first.visible, first.locked), (visible, locked), "{name}"); + let b = first.geometric_bounds().unwrap(); + assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {want:?}"); + } + + // An envelope written live opens live and wraps by its bounds, its options its own. + let live = |doc: &mut Document| { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + wrapped(named(envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW), "Thing"), -3.0, true) + }; + let doc = over_area_type(live); + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), 1); + assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}"); + let top = back.layers[0].children().unwrap(); + assert!(matches!(top[1].kind, NodeKind::Envelope { .. }), "{text_out}"); + same_wraps(&wraps(top), &[(Some("Thing".into()), -3.0, true)]); +} + +/// The rectangle that keeps a blend written as its art wrapping by its bounds counts toward the +/// object limit, ahead of the art: one object short, the last step is left out with the limit's +/// warning; without room for the rectangle, the options are left out with the warning, and the +/// group does not take them. In an instance whose art holds area type, shown, hidden, in a hidden +/// group or written as its outlines, the rectangle is the group's first member, below that type: +/// area type below the instance wraps by its bounds after reopening, and the type in its art is not +/// wrapped by them. +#[test] +fn wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + // A blend alone, without a symbol definition, so the objects are the group, the rectangle and + // the steps. + let mut doc = Document::new(300.0, 200.0); + let keys = vec![ + Arc::new(square(&mut doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), + Arc::new(square(&mut doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, thing).unwrap(); + let steps = export_ai_editing(&doc, &opts()).unwrap(); + let steps = crate::ai_alone(&steps.program).unwrap().0.layers[0].children().unwrap()[0].children().unwrap().len() - 1; + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let all = export_within(&doc, &opts(), read).unwrap(); + assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", all.warnings); + let out = export_within(&doc, &opts(), read - 1).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings); + let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + let top = back.layers[0].children().unwrap(); + same_wraps(&wraps(top), &[(None, 4.5, false)]); + assert_eq!((top[0].name.as_deref(), top[0].extras().wrap), (Some("Thing"), None), "{text_out}"); + let members = top[0].children().unwrap(); + assert_eq!(members.len(), steps, "the rectangle and all but the last step: {text_out}"); + assert!(matches!(members[0].kind, NodeKind::Path { guide: false, .. }) && members[0].appearance.items.is_empty(), "{text_out}"); + let out = export_within(&doc, &opts(), read - steps - 1).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings); + let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + assert!(!text_out.contains("(AI11TextWrapOffset)"), "{text_out}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + assert!(wraps(back.layers[0].children().unwrap()).is_empty(), "{text_out}"); + + // Area type in the symbol's art, shown or hidden, of `words`, in a hidden group with `in_hidden`. + let make = |shown: bool, words: &'static str, in_hidden: bool| { + move |doc: &mut Document| { + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(2.0, Color::BLACK)); + t.runs = vec![TextRun::new(words, style(2.0, Color::BLACK))]; + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(-10.0, -10.0, -6.0, -6.0)) }; + t.xf = Affine::IDENTITY; + let mut t = text_node(doc, t); + t.visible = shown; + if in_hidden { + t = group(doc, vec![t], false); + t.visible = false; + } + let s = square(doc, Rect::new(6.0, 6.0, 10.0, 10.0), LEAF); + let art = group(doc, vec![t, s], false); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); + let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])); + n.isolate = true; + wrapped(named(n, "Thing"), 4.5, false) + } + }; + // Type of spaces alone is written as its outlines, which are not type. + for (what, shown, words, in_hidden) in + [("shown", true, "leaf", false), ("hidden", false, "leaf", false), ("in a hidden group", true, "leaf", true), ("spaces", true, " ", false)] + { + let doc = over_area_type(make(shown, words, in_hidden)); + let text_out = program(&doc); + assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{what}: {text_out}"); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), 1, "{what}"); + assert!(same_region(&before, &after), "{what}\n{before:?}\n{after:?}\n{text_out}"); + let g = &back.layers[0].children().unwrap()[1]; + assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{what}: {text_out}"); + assert_eq!(g.extras().wrap, None, "{what}: {text_out}"); + let first = &g.children().unwrap()[0]; + assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{what}: {text_out}"); + let mut resolved = back.clone(); + vectorcraft_doc::text::resolve_wrap(None, &mut resolved); + let mut inner = vec![]; + resolved.layers[0].children().unwrap()[1].walk(&mut |m| { + if let NodeKind::Text(t) = &m.kind { + inner.push((matches!(t.kind, TextKind::Area { .. }), m.visible, t.wrap.len())); + } + }); + let want: &[(bool, bool, usize)] = match what { + "shown" | "in a hidden group" => &[(true, true, 0)], + "hidden" => &[(true, false, 0)], + _ => &[], + }; + assert_eq!(inner, want, "{what}: {text_out}"); + } +} + +/// A blend with no keys, written as an empty group, has no bounds for a rectangle: its group keeps +/// the text wrap options, and they read back. +#[test] +fn live_art_without_bounds_keeps_its_text_wrap_on_the_group() { + let mut doc = Document::new(300.0, 200.0); + let spec = vectorcraft_doc::BlendSpec::default(); + let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: vec![], spec: Box::new(spec) }), "Thing"), 4.5, true); + assert_eq!(thing.geometric_bounds(), None); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, thing).unwrap(); + let text_out = program(&doc); + assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}"); + let back = read_back(&doc); + same_wraps(&wraps(back.layers[0].children().unwrap()), &[(Some("Thing".into()), 4.5, true)]); +} + +/// A symbol instance written as its art, whose art holds an envelope of area type beside a square, +/// wraps area type below it by its bounds after reopening. The envelope there is written as its art, +/// after the type written for it as a live envelope is taken back: the group has no text wrap +/// options, and its first member is the rectangle of the bounds. +#[test] +fn an_envelope_of_area_type_in_written_art_leaves_the_wrap_on_the_bounds() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let doc = over_area_type(|doc| { + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut envelope = envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW); + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK)); + t.runs = vec![TextRun::new("bent", style(10.0, Color::BLACK))]; + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(60.0, 30.0, 140.0, 70.0)) }; + t.xf = Affine::IDENTITY; + let t = text_node(doc, t); + let NodeKind::Envelope { content, .. } = &mut envelope.kind else { unreachable_envelope() }; + content.push(Arc::new(t)); + let s = square(doc, Rect::new(250.0, 150.0, 260.0, 160.0), LEAF); + let art = group(doc, vec![envelope, s], false); + doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); + let mut n = instance(doc, "Bent", Affine::IDENTITY); + n.isolate = true; + wrapped(named(n, "Thing"), 4.5, false) + }); + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), 1); + assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}"); + let g = &back.layers[0].children().unwrap()[1]; + assert_eq!(g.extras().wrap, None, "{text_out}"); + let mut live = 0; + g.walk(&mut |m| live += usize::from(matches!(m.kind, NodeKind::Envelope { .. }))); + assert_eq!(live, 0, "{text_out}"); + let first = &g.children().unwrap()[0]; + assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{text_out}"); +} + /// A clipping path inside art cut to a clipping object is written as its fills and its strokes, /// two objects: its text wrap options are written once, whether it has both or only strokes, and /// with its strokes when the region outside leaves nothing of its fills. diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index fcbf1e1b82..1b48697e32 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -289,7 +289,8 @@ pub(super) struct Writer<'a> { /// brushed stroke's pieces) the art being written is in. Text wrap options are written only /// outside them, since only the document's own objects wrap type. drawn: u32, - /// The type just written as outlines has its text wrap options on the rectangle of its bounds + /// The type just written as outlines, or the symbol instance or live object just written as a + /// group of its art, has its text wrap options on the rectangle of its bounds /// ([`Self::wrap_bounds`]), not in the group's dictionary. wrap_moved: bool, /// The brushes written ([`brushes`]). @@ -773,6 +774,8 @@ impl<'a> Writer<'a> { if !self.open_group("u") { return; } + let state = self.state; + let moved = self.wrap_on_bounds(n, state); // The canvas places an instance inside a symbol's art where the outer instance puts // it (9-slice guides, stains and patterns included), and this art doesn't move with it. self.wrote_fixed |= self.in_symbol; @@ -817,12 +820,13 @@ impl<'a> Writer<'a> { self.warn(SYMBOL_LIMIT); } } + self.wrap_moved = moved; self.end_group("U", xy); } NodeKind::Envelope { .. } if self.envelope(n, xy) => {} - NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES)), + NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true), NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { - self.drawn_art(n, xy, Some(LIVE)); + self.drawn_art(n, xy, Some(LIVE), true); } // Ruler guides are kept in the document's native copy only. NodeKind::RulerGuide { .. } => {} @@ -889,13 +893,17 @@ impl<'a> Writer<'a> { } /// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given. - fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>) { + /// With `bounds`, `n`'s text wrap options go on the rectangle of its bounds, the group's first + /// member ([`Self::wrap_on_bounds`]); without it, in the group's dictionary. + fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>, bounds: bool) { if !self.open_group("u") { return; } + let state = self.state; if let Some(w) = warning { self.warn(w); } + let moved = bounds && self.wrap_on_bounds(n, state); if self.nest < MAX_NEST { let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); self.nest += 1; @@ -906,9 +914,29 @@ impl<'a> Writer<'a> { self.drawn -= 1; self.nest -= 1; } + self.wrap_moved = moved; self.end_group("U", xy); } + /// In the group that object `n` is written as, when the group's dictionary would hold `n`'s text + /// wrap options: the rectangle of `n`'s bounds with them ([`Self::wrap_bounds`]), then lock and + /// hidden state `state` again. True when the group's dictionary is to leave the options out + /// ([`Self::wrap_moved`]), so the group wraps type by `n`'s bounds, as `n` does + /// ([`vectorcraft_doc::text::resolve_wrap`]), not by its members. Written before the group's + /// members, the rectangle is below any area type among them and does not wrap it. False, + /// writing nothing, when `n` has no finite bounds, and the group's dictionary keeps the options. + fn wrap_on_bounds(&mut self, n: &Node, state: Option<(bool, bool)>) -> bool { + let Some(w) = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return false }; + if finite_bounds(n).is_none() { + return false; + } + self.wrap_bounds(n, w); + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } + true + } + /// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]), /// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an /// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask @@ -1555,23 +1583,20 @@ impl<'a> Writer<'a> { for c in over { self.node(c); } - // Type wraps by its bounds: its text wrap options go on a rectangle of its bounds, the - // group's last member, and the group's dictionary leaves them out. - if let Some(w) = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) { - self.wrap_bounds(n, w); - self.wrap_moved = true; - } + // Type wraps by its bounds. + self.wrap_moved = self.wrap_on_bounds(n, state); if let Some((locked, hidden)) = state { self.state(locked, hidden); } self.end_group("U", xy); } - /// An unpainted closed rectangle at the geometric bounds of type `n`, the region its text wraps - /// around, with `n`'s lock and hidden state and text wrap options `w` in its dictionary. Nothing + /// An unpainted closed rectangle at the geometric bounds of type, a symbol instance or a live + /// object `n`, the region its text wraps around ([`vectorcraft_doc::text::resolve_wrap`]), with + /// `n`'s lock and hidden state and text wrap options `w` in its dictionary. Nothing /// when `n` has no finite bounds, or without room for it ([`Self::take_objects`]). fn wrap_bounds(&mut self, n: &Node, w: TextWrap) { - let Some(b) = n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return }; + let Some(b) = finite_bounds(n) else { return }; self.state(n.locked, !n.visible); let objects = self.objects; self.plain_object(&shapes::rectangle(b), FillRule::NonZero, None, None, Xy::PLAIN); @@ -1760,6 +1785,11 @@ impl<'a> Writer<'a> { } } +/// `n`'s geometric bounds, when they are finite. +fn finite_bounds(n: &Node) -> Option { + n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) +} + /// The gradient of paint `p`, when it has one. fn gradient(p: Option<&Paint>) -> Option<&vectorcraft_color::GradientPaint> { match p { diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index dbd906e7cd..09c6a33550 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -411,9 +411,10 @@ impl Writer<'_> { self.hidden -= 1; self.nest -= 1; // The distorted art, which takes the envelope's lock, visibility, transparency, name and - // opacity mask. + // opacity mask. The reader opens the envelope live, wrapping type by its bounds, so its text + // wrap options stay in the art's dictionary. self.state(n.locked, !n.visible); - self.drawn_art(n, xy, None); + self.drawn_art(n, xy, None, false); if !opened || outlines || self.left_out_since(charges) { let lines = self.body.split_off(start); self.give_back(charges, &lines); diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index f1fb10af78..9bc831e537 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -22,15 +22,15 @@ use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::text::MAX_AKI; use vectorcraft_doc::{ - AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection, - ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign, + AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, Kinsoku, KinsokuShoriType, LineCap, LineJoin, Mojikumi, Node, NodeId, + NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign, }; use vectorcraft_geom::{Affine, PathData, Point}; use crate::ps; /// What the text document holds of type, and what it leaves out. -pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; /// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. const STREAM_VERSION: u32 = 14; @@ -161,6 +161,10 @@ fn dict(pairs: Vec<(u32, V)>) -> V { V::Dict(pairs) } +/// The document's Kinsoku sets, in order, each by its name: a paragraph's key 27 is its set's index +/// here (0 Hard, 1 Soft), as the reader's `kinsoku_sets` reads them. +const KINSOKU_SETS: [&str; 2] = ["PhotoshopKinsokuHard", "PhotoshopKinsokuSoft"]; + /// A resource set: its resources, each `<< /0 resource >>`, and its display list. fn set(resources: Vec, display: bool) -> V { let mut d = vec![(0, V::List(resources.into_iter().map(|r| dict(vec![(0, r)])).collect()))]; @@ -401,7 +405,6 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { } let hangul = text.chars().any(|c| matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{FFA0}'..='\u{FFDC}')); - let pairs = text.chars().zip(text.chars().skip(1)).any(|(a, b)| vectorcraft_text::inseparable(a, b)); let held = ParaStyle { justify: p.justify, left_indent: p.left_indent, @@ -411,16 +414,16 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { space_after: p.space_after, hyphenate: p.hyphenate, direction: p.direction.filter(|d| *d == ParaDirection::RightToLeft), - // The composition of Japanese punctuation new type gets (Line-end Punctuation Half - // Width, Standard burasagari) isn't reported: it changes no other script's lines. + // The Mojikumi set new type gets (Line-end Punctuation Half Width) isn't reported: it + // changes no other script's lines. mojikumi: if p.mojikumi == Mojikumi::LineEndHalf { p.mojikumi } else { ParaStyle::default().mojikumi }, - burasagari: if p.burasagari == Burasagari::Standard { p.burasagari } else { ParaStyle::default().burasagari }, + kinsoku: p.kinsoku, + kinsoku_type: p.kinsoku_type, + burasagari: p.burasagari, + bunri_kinshi: p.bunri_kinshi, // The text document has no Korean Line Break Anywhere: it reads back off, which // changes only the lines of a paragraph with Hangul in it. korean_line_break_anywhere: p.korean_line_break_anywhere && !hangul, - // Nor Bunri-Kinshi: it reads back off, which changes only the lines of a paragraph - // with an inseparable pair in it. - bunri_kinshi: p.bunri_kinshi && !pairs, ..ParaStyle::default() }; *p != held @@ -756,6 +759,32 @@ impl TextDoc { (4, len(p.space_before)), (5, len(p.space_after)), (9, V::Bool(p.hyphenate)), + (23, V::Bool(p.bunri_kinshi)), + ( + 24, + V::Int(match p.burasagari { + Burasagari::None => 0, + Burasagari::Standard => 1, + Burasagari::Forced => 2, + }), + ), + ( + 25, + V::Int(match p.kinsoku_type { + KinsokuShoriType::PushInFirst => 0, + KinsokuShoriType::PushOutFirst => 1, + KinsokuShoriType::PushOutOnly => 2, + }), + ), + // The Kinsoku set: `/nil` for None, else its index in the document's sets ([`KINSOKU_SETS`]). + ( + 27, + match p.kinsoku { + Kinsoku::None => V::Name("nil"), + Kinsoku::Hard => V::Int(0), + Kinsoku::Soft => V::Int(1), + }, + ), ]; if rtl { d.push((33, V::Int(1))); @@ -1110,7 +1139,7 @@ impl TextDoc { (1, set(fonts, true)), (2, empty()), (3, empty()), - (4, empty()), + (4, set(KINSOKU_SETS.iter().map(|name| dict(vec![(0, V::Str((*name).into()))])).collect(), false)), (5, set(vec![normal_char], true)), (6, set(vec![normal_para], true)), (8, set(self.frames.iter().map(clone_v).collect(), false)), diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index d32ae4c177..67928785ad 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -581,6 +581,10 @@ struct Reader<'a> { blend_budget: usize, /// The group on `%_` lines an envelope's dictionary just took (see [`Reader::drop_envelope_art`]). envelope_art: Option, + /// The envelope dictionaries whose `AIDeformArtKey` block (`X=` … `X+`) is being read, as how + /// many frames were open with each one innermost, innermost last. The block's art is art: a + /// dictionary in it is read as it is in a container ([`Reader::end_obj`]). + envelope_blocks: Vec, /// Envelopes waiting for their drawn art, innermost last. envelopes: Vec, /// How many more envelopes and warped text objects this import may draw to check @@ -813,6 +817,7 @@ impl<'a> Reader<'a> { blend_record: None, blend_budget: BLEND_BUDGET, envelope_art: None, + envelope_blocks: Vec::new(), envelopes: Vec::new(), envelope_checks: super::envelope::MAX_CHECKED, envelope_spent: super::envelope::Spent::default(), diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 8e670b3f72..830e3a48d0 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -482,6 +482,13 @@ impl<'a> Reader<'a> { return Ok(()); } let Some(f) = self.frames.pop() else { return Ok(()) }; + let depth = self.frames.len(); + // A block left open ends with its dictionary, and envelopes still waiting in it keep their + // drawn art: nothing after the dictionary is theirs. + self.envelope_blocks.retain(|d| *d <= depth); + while let Some(p) = self.envelopes.pop_if(|p| p.depth > depth) { + self.warn(crate::import::ai::envelope::drawn_note(p.typed)); + } let Frame { kind, children, base, hidden, gs, pending_unread_fill, pending_unread_stroke, after, mesh_ended, state, .. } = f; let Kind::Obj(mut o) = kind else { return Ok(()) }; obj::close(&mut o, &mut self.stack, base); @@ -496,7 +503,10 @@ impl<'a> Reader<'a> { } self.after_object = after; self.mesh_ended = mesh_ended; - if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) { + // An object's dictionary in an envelope's `AIDeformArtKey` block is about the art before it + // there, as it is in a container: an envelope there is one of the outer envelope's contents. + let in_block = o.ty == "ArtDictionary" && self.envelope_blocks.last() == Some(&depth); + if !in_block && matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) { return self.push(V::Obj(Rc::new(*o))); } match o.ty.as_str() { diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 8c032d5d83..721a6988ba 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -41,8 +41,19 @@ impl<'a> Reader<'a> { } /// `X=` in a `/Mask` dictionary: the opacity mask's art starts, read until its `X+` - /// ([`Self::end_mask`]). + /// ([`Self::end_mask`]). In an envelope's dictionary, its `AIDeformArtKey` block starts + /// ([`Reader::envelope_blocks`]). fn open_mask_object(&mut self, hidden: bool) -> Result<(), String> { + if let Some(Frame { kind: Kind::Obj(o), .. }) = self.frames.last() + && o.ty == "ArtDictionary" + && o.get("AIDeformOptionsKey").is_some() + { + // One entry for each open dictionary, however many `X=` it has. + if self.envelope_blocks.last() != Some(&self.frames.len()) { + self.envelope_blocks.push(self.frames.len()); + } + return Ok(()); + } if !matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(o), .. }) if o.ty == "Mask") { // `X=` also introduces legacy text frame art, read by `text_frames`. return Ok(()); @@ -63,6 +74,22 @@ impl<'a> Reader<'a> { self.open(Kind::Mask, hidden) } + /// `X+`: a dictionary's art block ends. The block of a dictionary whose `X=` opened no frame (an + /// envelope's, in an opacity mask's art too) ends with the dictionary still innermost; an opacity + /// mask's ends its art ([`Self::end_mask`]). + fn end_block(&mut self) -> Result<(), String> { + if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) { + if self.envelope_blocks.last() == Some(&self.frames.len()) { + self.envelope_blocks.pop(); + } + return Ok(()); + } + if self.frames.iter().any(|f| matches!(f.kind, Kind::Mask)) { + return self.end_mask(); + } + Ok(()) + } + /// `LB`: a graph started in this layer that hasn't ended doesn't go on past it; the layer ends. fn layer_end(&mut self) -> Result<(), String> { if self.graph.as_ref().is_some_and(|g| g.frames >= self.frames.len()) { @@ -159,8 +186,7 @@ impl<'a> Reader<'a> { } ";" => return self.end_obj(), "X=" => return self.open_mask_object(hidden), - "X+" if self.frames.iter().any(|f| matches!(f.kind, Kind::Mask)) => return self.end_mask(), - "X+" => return Ok(()), + "X+" => return self.end_block(), _ => {} } self.state_block_continues(w); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 7013468d25..f133a9ee03 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -8620,6 +8620,224 @@ fn an_envelope_off_the_page_opens_live_when_it_draws_close_to_its_drawn_art() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } +/// `art` on `%_` lines, as the editing data writer hides it: a line already on one stays as it is. +fn hidden_once(art: &str) -> String { + art.lines().map(|l| if l.starts_with("%_") { format!("{l}\n") } else { format!("%_{l}\n") }).collect() +} + +/// A mesh envelope of `content` shaped by the grid `shape`, with Edit Contents on (`editing`: the +/// contents in the group before the dictionary, the grid in its `AIDeformArtKey` block) or off (the +/// other way round, the contents in a plain group), then `drawn` and the plugin's `XP`. An envelope +/// record in `content` keeps its own `%_` lines. +fn mesh_envelope(shape: &str, editing: bool, content: &str, drawn: &str) -> String { + let keys = ENVELOPE_KEYS.replace("0 /Bool (AIDeformEditModeKey)", &format!("{} /Bool (AIDeformEditModeKey)", u8::from(editing))); + let (before, block) = if editing { (content.to_string(), shape.to_string()) } else { (shape.to_string(), format!("u\n{content}U\n9 () XW\n")) }; + format!( + "{}%_/ArtDictionary :\n{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden_once(&format!("u\n{before}U\n")), + commented(&keys), + hidden_once(&block), + ) +} + +/// The mesh envelope that maps the box 40 20 160 80 onto itself, and what it draws of +/// [`envelope_content`]. +fn flat_mesh() -> (String, vectorcraft_doc::live::EnvelopeKind, String) { + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let drawn = drawn_content(&flat); + (straight_mesh(1, 1, (120.0, 60.0)), flat, drawn) +} + +/// An envelope inside another envelope's contents opens as a live envelope inside the live outer +/// one, with Edit Contents on or off at either level: each keeps its own kind, contents and Edit +/// Contents, and neither leaves a copy of its contents drawn beside it. +#[test] +fn an_envelope_in_an_envelope_s_contents_opens_live_inside_it() { + use vectorcraft_doc::live::EnvelopeKind; + let (shape, flat, drawn) = flat_mesh(); + let EnvelopeKind::Mesh { points, .. } = &flat else { panic!("{flat:?}") }; + for (outer_editing, inner_editing) in [(false, false), (false, true), (true, false), (true, true)] { + let why = format!("outer editing {outer_editing}, inner editing {inner_editing}"); + let inner = mesh_envelope(&shape, inner_editing, &envelope_content(), &drawn); + let r = read_ok(&layer(&mesh_envelope(&shape, outer_editing, &hidden_once(&inner), &format!("u\n{drawn}U\n")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{why}: {a:#?}"); + let flat_points = |kind: &EnvelopeKind| match kind { + EnvelopeKind::Mesh { rows: 1, cols: 1, points, .. } => Some(points.clone()), + _ => None, + }; + let (content, kind, _, editing, _) = live_envelope(&a[0]); + assert_eq!((flat_points(kind), editing), (Some(points.clone()), outer_editing), "{why}: {kind:?}"); + assert_eq!(content.len(), 1, "{why}: {content:#?}"); + let (inner, kind, _, editing, _) = live_envelope(&content[0]); + assert_eq!((flat_points(kind), editing), (Some(points.clone()), inner_editing), "{why}: {kind:?}"); + assert_eq!(inner.len(), 1, "{why}: {inner:#?}"); + assert!(matches!(inner[0].kind, NodeKind::Path { .. }), "{why}: {inner:#?}"); + assert_eq!(fill(&inner[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "{why}"); + assert!(r.warnings.is_empty(), "{why}: {:?}", r.warnings); + } +} + +/// An outer envelope, Edit Contents off, whose `AIDeformArtKey` block holds `block` as it is, with no +/// plain group around it, shaped by the grid `shape` and drawn as `drawn`. +fn bare_block_envelope(shape: &str, block: &str, drawn: &str) -> String { + format!( + "{}%_/ArtDictionary :\n{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden_once(&format!("u\n{shape}U\n")), + commented(ENVELOPE_KEYS), + hidden_once(block), + ) +} + +/// An envelope record straight in another envelope's `AIDeformArtKey` block, with no group around +/// it, opens live inside the live outer envelope too. Two of them there are both its contents. +#[test] +fn an_envelope_straight_in_an_envelope_s_block_opens_live_inside_it() { + let (shape, _, drawn) = flat_mesh(); + let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)); + let r = read_ok(&layer(&bare_block_envelope(&shape, &inner, &format!("u\n{drawn}U\n")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 1, "{content:#?}"); + let (inner_content, ..) = live_envelope(&content[0]); + assert!(matches!(inner_content[0].kind, NodeKind::Path { .. }), "{inner_content:#?}"); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + // Two envelopes side by side in the block: both are the outer envelope's contents, each live. + let two = format!("{inner}{inner}"); + let r = read_ok(&layer(&bare_block_envelope(&shape, &two, &format!("u\n{drawn}U\nu\n{drawn}U\n")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 2, "{content:#?}"); + content.iter().for_each(|c| _ = live_envelope(c)); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// An object's own dictionary straight in an envelope's block, with no group around them, names it +/// there. +#[test] +fn an_object_s_dictionary_straight_in_an_envelope_s_block_names_it() { + let (shape, _, drawn) = flat_mesh(); + let block = format!("{}/ArtDictionary :\n(Box) /String (AIArtName) ,\n;\n", envelope_content()); + let r = read_ok(&layer(&bare_block_envelope(&shape, &block, &format!("u\n{drawn}U\n")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 1, "{content:#?}"); + assert_eq!(content[0].name.as_deref(), Some("Box"), "{content:#?}"); +} + +/// An inner envelope that doesn't open live keeps its drawn art inside the live outer envelope, +/// drawn once, without its own source art: one whose drawn art differs from what it draws, and one +/// whose record doesn't read (a style number past the list). The outer envelope maps that drawn +/// art's box onto its grid. An outer envelope that doesn't match its drawn art keeps that drawn +/// art, and nothing of its record is drawn. +#[test] +fn a_nested_envelope_that_doesn_t_open_live_keeps_its_drawn_art() { + let (shape, _, drawn) = flat_mesh(); + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let unread = mesh_envelope(&shape, false, &envelope_content(), &drawn).replace("%_2 /Int (AIDeformStyle)", "%_9 /Int (AIDeformStyle)"); + for (why, inner) in [("drawn elsewhere", mesh_envelope(&shape, false, &envelope_content(), &shifted)), ("unread", unread)] { + for bare in [false, true] { + let inner = hidden_once(&inner); + let outer_drawn = format!("u\n{drawn}U\n"); + let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) }; + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{why}, bare {bare}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Envelope { .. }), "{why}, bare {bare}: {:?}", r.warnings); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 1, "{why}, bare {bare}: {content:#?}"); + // The inner envelope's drawn art: its group of one path, or, straight in the block, the + // path, as the plain group around a block's only object is the block's own. + let drawn_path = if bare { + &content[0] + } else { + let kids = content[0].children().unwrap_or_else(|| panic!("{why}: {content:#?}")); + assert_eq!(kids.len(), 1, "{why}: {content:#?}"); + &kids[0] + }; + assert!(matches!(drawn_path.kind, NodeKind::Path { .. }), "{why}, bare {bare}: {content:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN], "{why}, bare {bare}"); + } + } + // The outer envelope's drawn art lies elsewhere: it stays, as one group, the inner record with it. + let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)); + for bare in [false, true] { + let outer_drawn = format!("u\n{shifted}U\n"); + let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) }; + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "bare {bare}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "bare {bare}: {a:#?}"); + assert_eq!(a[0].geometric_bounds(), Some(Rect::new(42.0, 20.0, 162.0, 80.0)), "bare {bare}"); + assert_eq!(r.warnings, [super::envelope::DRAWN], "bare {bare}"); + } +} + +/// Broken nested records read without taking another record's place: an inner `X=` with no `X+` +/// (the inner envelope still opens live), an inner dictionary with no group before it (its drawn art +/// stays), and an `XP` repeated after the inner one. The outer envelope, whose own record is whole, +/// still opens live around what the inner one left. +#[test] +fn broken_nested_envelope_records_keep_the_outer_envelope() { + let (shape, _, drawn) = flat_mesh(); + let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)); + let no_end = inner.replacen("%_X+\n", "", 1); + let no_group = inner.replacen(&hidden_once(&format!("u\n{shape}U\n")), "", 1); + let twice = inner.replace("%_(Adobe Deform Plugin) 1 0 0 XP\n", "%_(Adobe Deform Plugin) 1 0 0 XP\n%_(Adobe Deform Plugin) 1 0 0 XP\n"); + for (why, inner, live) in [("no X+", no_end, true), ("no group", no_group, false), ("XP twice", twice, true)] { + for bare in [false, true] { + let outer_drawn = format!("u\n{drawn}U\n"); + let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) }; + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{why}, bare {bare}: {a:#?}"); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 1, "{why}, bare {bare}: {content:#?}"); + assert_eq!(matches!(content[0].kind, NodeKind::Envelope { .. }), live, "{why}, bare {bare}: {content:#?}"); + } + } +} + +/// An inner envelope whose `XP` is missing stops waiting when the outer envelope's dictionary ends: +/// a stray `XP` in a later group leaves that group's art as it is. +#[test] +fn an_inner_envelope_without_its_xp_does_not_take_later_art() { + let (shape, _, drawn) = flat_mesh(); + let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)).replace("%_(Adobe Deform Plugin) 1 0 0 XP\n", ""); + let later = format!("u\nu\n{drawn}U\n(Adobe Deform Plugin) 1 0 0 XP\nU\n"); + let r = read_ok(&layer(&format!("{}{later}", bare_block_envelope(&shape, &inner, &format!("u\n{drawn}U\n"))))); + let a = art(&r.doc); + assert_eq!(a.len(), 2, "{a:#?}"); + live_envelope(&a[0]); + let kids = a[1].children().unwrap_or_else(|| panic!("{a:#?}")); + assert!(matches!(kids[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN], "{:?}", r.warnings); +} + +/// An envelope in an opacity mask's art reads: its block's `X+` ends the block, not the mask's art. +#[test] +fn an_envelope_in_an_opacity_mask_s_art_reads() { + let (shape, _, drawn) = flat_mesh(); + let owner = format!("{RED}{}f\n", rect_path(10.0, 20.0, 170.0, 90.0)); + let envelope = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)); + let mask = format!( + "%_/ArtDictionary :\n%_/Mask :\n%_1 /Bool (Linked) ,\n%_X=\n%_u\n{envelope}%_U\n%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_0 /Bool (Inverted) ,\n%_0 /Bool (Disabled) ,\n%_; (AI9_Mask) ,\n%_;\n" + ); + let r = read_ok(&layer(&format!("{owner}{mask}"))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let m = a[0].extras().mask.as_ref().unwrap_or_else(|| panic!("{a:#?}")); + assert_eq!(m.art.geometric_bounds(), Some(Rect::new(40.0, 20.0, 160.0, 80.0)), "{:#?}", m.art); +} + #[test] fn a_gradient_mesh_reads_as_a_patch() { let corner = |rgb: &str, x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| { diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 403cbc5431..71b65e65d0 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -859,7 +859,9 @@ impl Exporter<'_> { /// Opens the blend mode and the transparency group `n` is drawn with (`container` when it is a /// group or layer whose children `knockout` each other). Returns how many were opened, and /// whether the children are to be drawn in an isolated group of their own: the knockout group of -/// an unclipped group's elements is its isolated group too. +/// an unclipped group's elements is its isolated group too. An opaque knockout group in Normal +/// mode that does not isolate opens no group: its elements are drawn on the art below it, in a +/// knockout group without `/I` when there are several. fn transparency(s: &mut Surface, n: &Node, page: Rect, container: bool, knockout: bool) -> (usize, bool) { let mut pushes = 0; if n.blend != BlendMode::Normal { @@ -876,6 +878,8 @@ fn transparency(s: &mut Surface, n: &Node, page: Rect, container: bool, knockout } else if n.opacity < 1.0 { s.push_opacity(norm(n.opacity)); pushes += 1; + } else if knockout && !n.isolate && n.blend == BlendMode::Normal { + // A knockout group that does not isolate: its elements start from the art below it. } else if knockout && matches!(n.kind, NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. }) { isolated_children = true; } else { diff --git a/crates/pdf/src/tests/blend.rs b/crates/pdf/src/tests/blend.rs index c55a0b7504..1cd5c949e0 100644 --- a/crates/pdf/src/tests/blend.rs +++ b/crates/pdf/src/tests/blend.rs @@ -151,6 +151,77 @@ fn a_knockout_group_is_written_as_one_pdf_knockout_group() { } } +/// A knockout group with nothing blending inside is drawn in an isolated group (`/I true`) only +/// when the group isolates, clipped or not, with opaque or translucent elements, and reads back +/// knocking out. +#[test] +fn a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates() { + for clip in [false, true] { + for opacity in [0.5, 1.0] { + for isolate in [false, true] { + let mut d = knockout_squares(3, false, isolate); + let g = d.layers[0].children().unwrap()[1].id; + let mut squares: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec(); + for s in &mut squares { + std::sync::Arc::make_mut(s).opacity = opacity; + } + if clip { + let c = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(10.0, 10.0, 190.0, 190.0)), + Appearance::basic(Paint::None, Paint::None, 0.0), + ); + squares.insert(0, std::sync::Arc::new(c)); + } + d.node_mut(g).unwrap().kind = vectorcraft_doc::NodeKind::Group { children: squares, clip }; + let case = format!("clip {clip}, opacity {opacity}, isolate {isolate}"); + let t = text(&d); + assert_eq!(t.matches("/Ktrue").count(), 1, "{case}"); + // Each translucent element is an isolated form with its opacity. + let elements = if opacity < 1.0 { 3 } else { 0 }; + assert_eq!(t.matches("/Itrue").count(), elements + usize::from(isolate), "{case}"); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("{case}: {e}")); + let mut found = vec![]; + back.walk(|n| { + if n.knockout == vectorcraft_doc::Knockout::On { + found.push(n.isolate); + } + }); + assert_eq!(found, [false], "{case}"); + } + } + } +} + +/// An overprinting element of a knockout group that does not isolate is drawn in a `/K` group +/// without `/I true`, so it overprints the art below the group, and its graphics state still +/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`. +#[test] +fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below() { + for isolate in [false, true] { + let mut d = knockout_squares(3, false, isolate); + let g = d.layers[0].children().unwrap()[1].id; + let squares: Vec<_> = d.node(g).unwrap().children().unwrap().iter().map(|s| s.id).collect(); + for s in &squares { + d.node_mut(*s).unwrap().opacity = 1.0; + } + d.node_mut(squares[2]).unwrap().appearance.fill_mut().unwrap().overprint = true; + let t = text(&d); + assert_eq!(t.matches("/Ktrue").count(), 1, "isolate {isolate}"); + assert_eq!(t.matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + assert!(t.contains("/OPtrue/optrue/OPM1"), "isolate {isolate}"); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("isolate {isolate}: {e}")); + let mut overprints = vec![]; + back.walk(|n| { + if let Some(f) = n.appearance.fill() { + overprints.push(f.overprint); + } + }); + assert_eq!(overprints, [false, false, false, true], "isolate {isolate}"); + assert_eq!(knockout_groups(&back), [3], "isolate {isolate}"); + } +} + /// The knockout group of an isolated group is isolated too (`/I true` beside `/K true`), and the /// group reads back as isolated and knocking out. (Each translucent element is a group of its own.) #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1ab327d3b2..875e8025a1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -97,6 +97,7 @@ pub mod plugin; mod png_options; pub mod print; pub mod print_presets; +pub mod psd_import; mod psd_options; pub mod raster_effects; pub mod rearrange_artboards; @@ -417,6 +418,7 @@ registry! { PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC, SafeMode: [safe_mode::KIND] => safe_mode::SPEC, DxfImport: [dxf_import::KIND] => dxf_import::SPEC, + PsdImport: [psd_import::KIND] => psd_import::SPEC, RasterFormatOptions: ["tiffOptions", "bmpOptions", "tgaOptions"] => png_options::SPEC, SaveForWeb: [save_for_web::KIND] => save_for_web::SPEC, PsdOptions: ["psdOptions"] => png_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs new file mode 100644 index 0000000000..75fd0e0f11 --- /dev/null +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -0,0 +1,585 @@ +//! PSD Import Options: opening a PSD or PSB file with two or more layers or with slices, or +//! placing one without Link, asks whether its layers become objects or one flat image, whether +//! hidden layers come in, and whether its slices come in (Import Slices, offered only for a file +//! with slices) +//! (). +//! A linked file shows its flat image, so placing with Link doesn't ask. The two-layer threshold, +//! the starting choices, Import Slices applying to both conversions and remembering the choices +//! are VectorCraft's own. +//! +//! Fields: `mode` (`open` | `place`), `name`, `path?`, `width`, `height` (the canvas, px), +//! `layers`, `hidden` and `slices` (counts, from `document.psdInfo`), `convert` (`objects` | +//! `flatten`), `hiddenLayers` and `importSlices`. `__place` keeps the other `file.place` params. +//! The file's bytes stay in [`crate::state::UiState::dialog_file`]. OK opens or places the file +//! with `layers`, `hiddenLayers` and (for a file with slices) `importSlices`, and remembers the +//! choices for the next file; errors keep the dialog open. + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::fileio; + +use super::DialogSpec; +use super::import_pdf::{DialogFile, other_place_params, place_source, with_file}; +use crate::state::Dialog; +use crate::{VectorcraftApp, io, widgets}; + +pub const KIND: &str = "psdImport"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |d| if d.str("mode") == "place" { tl!("Place PSD") } else { tl!("PSD Import Options") }.into(), + body, + confirm, + min_width: 380.0, + ..DialogSpec::FORM +}; + +/// The fewest layers a file has for the dialog to ask. +const MIN_LAYERS: usize = 2; + +/// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they +/// are a PSD or PSB file with [`MIN_LAYERS`] layers or more, or with slices; false when they aren't +/// (the loader then opens or places the file, or says why it can't). +pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, place: Option<&Value>) -> bool { + let Ok(info) = fileio::psd_info(bytes) else { return false }; + if info.layers < MIN_LAYERS && info.slices == 0 { + return false; + } + app.ui.dialog_file = Some(DialogFile::new(bytes.to_vec())); + let (layers, hidden, slices) = last_choices(app); + let mut fields = json!({ + "mode": if place.is_some() { "place" } else { "open" }, + "name": name, + "width": info.width, + "height": info.height, + "layers": info.layers, + "hidden": info.hidden, + "slices": info.slices, + "convert": if layers { "objects" } else { "flatten" }, + "hiddenLayers": hidden, + "importSlices": slices, + }); + if let Some(p) = path { + fields["path"] = json!(p); + } + if let Some(p) = place { + fields["__place"] = other_place_params(p, &["layers", "hiddenLayers", "importSlices"]); + } + app.ui.dialog = Some(Dialog::new(KIND, fields)); + true +} + +/// `file.place` with params `p` asks first (true) when they embed a PSD or PSB file (`link: false`, +/// or the file's bytes) and give no `layers`. +pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool { + let embedded = p.get("path").is_none() || p.get("link").and_then(Value::as_bool) == Some(false); + if !embedded || p.get("layers").is_some() { + return false; + } + let Some((name, bytes, path)) = place_source(app, p, |ext| matches!(ext, "psd" | "pdd" | "psb")) else { return false }; + offer(app, &name, &bytes, path, Some(p)) +} + +/// The PSD Import Options chosen last (layers, hidden layers, slices), at first Convert Layers to +/// Objects without hidden layers, with Import Slices. +fn last_choices(app: &VectorcraftApp) -> (bool, bool, bool) { + let last = |k: &str, default: bool| app.ui.psd_import.get(k).and_then(Value::as_bool).unwrap_or(default); + (last("layers", true), last("hiddenLayers", false), last("importSlices", true)) +} + +/// Several files placed without Link load the place cursor without asking: the `file.place.queue` +/// params `q` take the PSD Import Options chosen last, which apply to each PSD or PSB file among them. +pub fn queue_options(app: &VectorcraftApp, q: &mut Value) { + let (layers, hidden, slices) = last_choices(app); + q["layers"] = json!(layers); + if layers && hidden { + q["hiddenLayers"] = json!(true); + } + q["importSlices"] = json!(slices); +} + +/// `file.place` params `p` placed without asking (Show Import Options off) that embed a PSD or PSB +/// file and give no `layers` take the PSD Import Options chosen last; `hiddenLayers` and +/// `importSlices` that the params give are kept. +pub fn last_options(app: &VectorcraftApp, p: &mut Value) { + let embedded = p.get("path").is_none() || p.get("link").and_then(Value::as_bool) == Some(false); + let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default(); + if embedded && p.get("layers").is_none() && matches!(fileio::extension(name).as_str(), "psd" | "pdd" | "psb") { + let (layers, hidden, slices) = last_choices(app); + p["layers"] = json!(layers); + if layers && hidden && p.get("hiddenLayers").is_none() { + p["hiddenLayers"] = json!(true); + } + if p.get("importSlices").is_none() { + p["importSlices"] = json!(slices); + } + if p.get("path").is_none() { + // A file from bytes has no file to link to; it may carry the Place dialog's Link. + p["link"] = json!(false); + } + } +} + +/// OK: open or place the file with the choices. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let file = app.ui.dialog_file.clone().ok_or("the file is no longer loaded")?; + let layers = d.str("convert") != "flatten"; + let hidden = layers && d.bool("hiddenLayers"); + // Import Slices is a choice only for a file with slices; otherwise the one made last stays. + let has_slices = d.fields.get("slices").and_then(Value::as_u64).unwrap_or(0) > 0; + let slices = if has_slices { d.bool("importSlices") } else { last_choices(app).2 }; + app.ui.psd_import = json!({ "layers": layers, "hiddenLayers": d.bool("hiddenLayers"), "importSlices": slices }); + let r = if d.str("mode") == "place" { + let mut p = with_file(d.fields.get("__place"), d, &file); + p["layers"] = json!(layers); + if layers || has_slices { + // Layers and slices are always embedded; a file from bytes may carry the Place dialog's + // Link. + p["link"] = json!(false); + } + if hidden { + p["hiddenLayers"] = json!(true); + } + if has_slices { + p["importSlices"] = json!(slices); + } + crate::place::run_for_user(app, &p).map(|_| ()) + } else { + let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); + let mut p = json!({ "layers": layers, "hiddenLayers": hidden }); + if has_slices { + p["importSlices"] = json!(slices); + } + io::open_document(app, &d.str("name"), &file.bytes, path, &p).map(|_| ()) + }; + match r { + Ok(()) => { + // Placing may have opened another dialog; only this one closes. + if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) + } + Err(e) => { + app.ui.dialog = Some(d.clone()); + Err(e) + } + } +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); + widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers"))); + // Offered only for a file with slices, with either conversion. + let sliced = count("slices") > 0; + ui.add_space(8.0); + let convert = d.str("convert") != "flatten"; + if widgets::radio(ui, tl!("Convert Layers to Objects"), convert, true) { + d.fields.insert("convert".into(), json!("objects")); + } + ui.horizontal(|ui| { + ui.add_space(22.0); + let on = d.bool("hiddenLayers"); + if widgets::check(ui, tl!("Import Hidden Layers"), on && convert, convert) { + d.fields.insert("hiddenLayers".into(), json!(!on)); + } + }); + if widgets::radio(ui, tl!("Flatten Layers to a Single Image"), !convert, true) { + d.fields.insert("convert".into(), json!("flatten")); + } + ui.add_space(8.0); + let on = d.bool("importSlices"); + if widgets::check(ui, tl!("Import Slices"), on && sliced, sliced) { + d.fields.insert("importSlices".into(), json!(!on)); + } + false +} + +#[cfg(test)] +mod tests { + use vectorcraft_engine::Session; + use vectorcraft_engine::doc::NodeKind; + + use super::*; + + /// A PSD file of three layers, the middle one hidden, written by `document.export`. + fn layered() -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + let back = s.doc().unwrap().doc.layers[0].id.0; + s.execute("layer.setProps", &json!({"id": back, "name": "Back"})).unwrap(); + for (name, color) in [("Back", "#ff0000"), ("Middle", "#00ff00"), ("Front", "#0000ff")] { + if name != "Back" { + s.execute("layer.new", &json!({ "name": name })).unwrap(); + } + s.execute("paint.setFill", &json!({ "color": color })).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + } + let middle = s.doc().unwrap().doc.layers[1].id.0; + s.execute("layer.setProps", &json!({"id": middle, "visible": false})).unwrap(); + let r = s.execute("document.export", &json!({"format": "psd", "hiddenLayers": true})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() + } + + fn app() -> VectorcraftApp { + VectorcraftApp::new(Session::new(), Default::default()) + } + + fn frame(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + } + + fn layer_names(app: &VectorcraftApp) -> Vec<(String, bool)> { + app.session.doc().unwrap().doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect() + } + + #[test] + fn opening_a_layered_file_asks_for_the_import_options() { + let psd = layered(); + let mut app = app(); + io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("mode"), d.str("convert"), d.bool("hiddenLayers")), (KIND, "open".into(), "objects".into(), false)); + assert_eq!((&d.fields["layers"], &d.fields["hidden"], &d.fields["width"]), (&json!(3), &json!(1), &json!(20))); + assert!(app.session.active().is_none(), "nothing opens before OK"); + let text = frame(&mut app); + for label in [ + "PSD Import Options", + "20 × 20 px", + "Layers: 3", + "Convert Layers to Objects", + "Import Hidden Layers", + "Flatten Layers to a Single Image", + "OK", + ] { + assert!(text.contains(label), "{label} in {text}"); + } + // Layers as objects, hidden ones left out. + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Front".to_string(), true)]); + // With Import Hidden Layers the hidden layer comes in hidden. + io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); + set(&mut app, "hiddenLayers", json!(true)); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Middle".to_string(), false), ("Front".to_string(), true)]); + // Flatten opens one image, and the next file starts from the choices made last. + io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("hiddenLayers"), "remembered"); + set(&mut app, "convert", json!("flatten")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.layers.len(), 1); + assert!(matches!(st.doc.layers[0].children().map(Vec::as_slice), Some([one]) if matches!(one.kind, NodeKind::Image(_)))); + io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("convert"), "flatten"); + } + + #[test] + fn files_with_fewer_than_two_layers_open_without_asking() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let one = s.execute("document.export", &json!({"format": "psd"})).unwrap(); + let flat = s.execute("document.export", &json!({"format": "psd", "layers": false})).unwrap(); + for r in [one, flat] { + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let mut app = app(); + io::open_bytes(&mut app, "one.psd", &bytes, None).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(app.session.active().is_some()); + } + } + + #[test] + fn placing_without_link_asks_and_places_the_layers_as_a_group() { + let b64 = vectorcraft_format::base64_encode(&layered()); + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap(); + assert_eq!(r["dialog"], KIND); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("mode"), &d.fields["__place"]), ("place".into(), &json!({"at": [50, 50]}))); + assert!(frame(&mut app).contains("Place PSD")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is selected") }; + let g = st.doc.node(id).unwrap(); + assert!(matches!(g.kind, NodeKind::Group { .. })); + let names: Vec<&str> = g.children().unwrap().iter().filter_map(|c| c.name.as_deref()).collect(); + assert_eq!(names, ["Back", "Front"]); + // Flatten places the merged image. + crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap(); + set(&mut app, "convert", json!("flatten")); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is selected") }; + assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Image(_))); + } + + #[test] + fn several_files_placed_without_link_take_the_last_choices() { + let dir = std::env::temp_dir().join(format!("vc-psd-import-queue-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let paths: Vec = ["a.psd", "b.psd"] + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, layered()).unwrap(); + p.to_string_lossy().into_owned() + }) + .collect(); + // Place both through the Place dialog, then click the cursor once for each: what was placed. + let place_two = |app: &mut VectorcraftApp, link: bool| -> Vec { + let files: Vec = paths.iter().map(|p| json!({ "path": p })).collect(); + let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": link, "template": false})); + crate::place::confirm(app, &d).unwrap(); + assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + let view = vectorcraft_engine::ViewInfo::default(); + (0..2) + .map(|_| { + for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() { + if let vectorcraft_engine::UiRequest::Place(p) = r { + crate::place::place_from_cursor(app, &p); + } + } + } + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is placed") }; + st.doc.node(id).unwrap().clone() + }) + .collect() + }; + let visible = |n: &vectorcraft_engine::doc::Node| -> Vec { n.children().unwrap().iter().map(|c| c.visible).collect() }; + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // At first, Convert Layers to Objects without hidden layers. + for n in place_two(&mut app, false) { + assert!(matches!(n.kind, NodeKind::Group { .. })); + assert_eq!(visible(&n), [true, true]); + } + // Then the choices made last. + app.ui.psd_import = json!({"layers": true, "hiddenLayers": true}); + for n in place_two(&mut app, false) { + assert_eq!(visible(&n), [true, false, true]); + } + app.ui.psd_import = json!({"layers": false, "hiddenLayers": true}); + assert!(place_two(&mut app, false).iter().all(|n| matches!(n.kind, NodeKind::Image(_)))); + // Placed with Link, the files keep their flat images. + app.ui.psd_import = json!({"layers": true, "hiddenLayers": false}); + assert!(place_two(&mut app, true).iter().all(|n| matches!(n.kind, NodeKind::Image(_)))); + std::fs::remove_dir_all(&dir).ok(); + } + + /// `psd` with a slices resource (1050, version 6) holding one user slice over its top-left + /// 10 × 10 px, named "cell". + fn sliced(psd: &[u8]) -> Vec { + let ustr = |s: &str| -> Vec { + let units: Vec = s.encode_utf16().collect(); + let mut b = (units.len() as u32).to_be_bytes().to_vec(); + b.extend(units.iter().flat_map(|u| u.to_be_bytes())); + b + }; + let mut data = 6u32.to_be_bytes().to_vec(); + data.extend([0u8; 16]); + data.extend(ustr("")); + data.extend(1u32.to_be_bytes()); + // ID, group ID, origin (made by the user), name, type (Image), left, top, right, bottom. + data.extend([1u32, 0, 2].iter().flat_map(|v| v.to_be_bytes())); + data.extend(ustr("cell")); + data.extend([1u32, 0, 0, 10, 10].iter().flat_map(|v| v.to_be_bytes())); + // URL, target, message, alt text, cell text is HTML, cell text, alignments, color. + for _ in 0..4 { + data.extend(ustr("")); + } + data.push(0); + data.extend(ustr("")); + data.extend([0u8; 12]); + let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize; + let colors = 26 + 4 + u32_at(26); + let len = u32_at(colors); + let mut block = b"8BIM".to_vec(); + block.extend(1050u16.to_be_bytes()); + block.extend([0, 0]); + block.extend((data.len() as u32).to_be_bytes()); + block.extend(&data); + block.resize(block.len().next_multiple_of(2), 0); + let mut out = psd[..colors].to_vec(); + out.extend(((len + block.len()) as u32).to_be_bytes()); + out.extend(&psd[colors + 4..colors + 4 + len]); + out.extend(block); + out.extend(&psd[colors + 4 + len..]); + out + } + + fn slice_names(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.slices.iter().map(|s| s.options.name.clone()).collect() + } + + #[test] + fn a_file_with_slices_asks_with_import_slices_on_either_conversion() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let r = s.execute("document.export", &json!({"format": "psd"})).unwrap(); + // One layer: without slices it opens at once, with them it asks. + let psd = sliced(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + let mut app = app(); + io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), &d.fields["slices"], d.bool("importSlices")), (KIND, &json!(1), true)); + assert!(frame(&mut app).contains("Import Slices")); + // Flatten keeps Import Slices: the merged image opens with the slice. + set(&mut app, "convert", json!("flatten")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(slice_names(&app), ["cell"]); + // Left off, the slice stays out, and the next file starts from that choice. + io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); + set(&mut app, "importSlices", json!(false)); + super::super::confirm(&mut app).unwrap(); + assert!(slice_names(&app).is_empty()); + io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().bool("importSlices"), "remembered"); + // A layered file without slices keeps the choice made last for the next sliced one. + app.ui.dialog = None; + io::open_bytes(&mut app, "poster.psd", &layered(), None).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["slices"], json!(0)); + set(&mut app, "importSlices", json!(true)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.ui.psd_import["importSlices"], json!(false)); + } + + #[test] + fn placing_a_sliced_file_without_link_brings_its_slices_with_the_art() { + let b64 = vectorcraft_format::base64_encode(&sliced(&layered())); + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("importSlices")); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.slices.len(), 1); + assert_eq!(st.doc.slices[0].rect, vectorcraft_geom::Rect::new(40.0, 40.0, 50.0, 50.0)); + // Several files placed together take the choice made last. + let mut q = json!({}); + app.ui.psd_import = json!({"layers": true, "importSlices": false}); + queue_options(&app, &mut q); + assert_eq!(q["importSlices"], json!(false)); + } + + #[test] + fn placing_with_show_import_options_off_takes_the_last_choices() { + let b64 = vectorcraft_format::base64_encode(&sliced(&layered())); + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // The file's bytes carry the Place dialog's Link, which they have no file for. + let place = |app: &mut VectorcraftApp, slices: Option| { + let mut p = json!({"name": "poster.psd", "dataBase64": b64, "link": true, "showImportOptions": false}); + if let Some(s) = slices { + p["importSlices"] = json!(s); + } + crate::place::run_for_user(app, &p).unwrap(); + assert!(app.ui.dialog.is_none(), "placed without asking"); + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is selected") }; + (st.doc.node(id).unwrap().kind.clone(), st.doc.slices.len()) + }; + // At first, Convert Layers to Objects with Import Slices. + let (kind, slices) = place(&mut app, None); + assert!(matches!(kind, NodeKind::Group { .. })); + assert_eq!(slices, 1); + // An `importSlices` the params give is kept. + let (kind, slices) = place(&mut app, Some(false)); + assert!(matches!(kind, NodeKind::Group { .. })); + assert_eq!(slices, 1, "no new slice"); + // Then the choices made last. + app.ui.psd_import = json!({"layers": false, "importSlices": false}); + let (kind, slices) = place(&mut app, None); + assert!(matches!(kind, NodeKind::Image(_))); + assert_eq!(slices, 1, "no new slice"); + let (_, slices) = place(&mut app, Some(true)); + assert_eq!(slices, 2, "the given importSlices brings the slice in"); + } + + #[test] + fn files_from_bytes_placed_with_link_take_the_last_choices() { + let files: Vec = ["a.psd", "b.psd"].iter().map(|n| json!({ "name": n })).collect(); + let mut app = app(); + for n in ["a.psd", "b.psd"] { + app.place.picked.push((n.to_string(), sliced(&layered()))); + } + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // The dialog's Link is on, but files from bytes have no file to link to. + let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": true, "template": false, "showImportOptions": false})); + crate::place::confirm(&mut app, &d).unwrap(); + assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + let view = vectorcraft_engine::ViewInfo::default(); + for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() { + if let vectorcraft_engine::UiRequest::Place(p) = r { + crate::place::place_from_cursor(&mut app, &p); + } + } + } + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is placed") }; + // At first, Convert Layers to Objects with Import Slices. + assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Group { .. })); + assert_eq!(st.doc.slices.len(), 1); + } + + #[test] + fn a_cursor_loaded_with_show_import_options_on_asks_for_each_psd_file() { + let dir = std::env::temp_dir().join(format!("vc-psd-import-asks-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let paths: Vec = ["a.psd", "b.psd"] + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, layered()).unwrap(); + p.to_string_lossy().into_owned() + }) + .collect(); + let files: Vec = paths.iter().map(|p| json!({ "path": p })).collect(); + let services = crate::Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // The choices made last would place the layers without asking with Show Import Options off. + app.ui.psd_import = json!({"layers": true, "importSlices": true}); + let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": false, "template": false, "showImportOptions": true})); + crate::place::confirm(&mut app, &d).unwrap(); + assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + assert_eq!(app.session.tool_options()["count"], 2); + // A click on the canvas: the file the cursor's request names asks. + let view = vectorcraft_engine::ViewInfo::default(); + for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() { + if let vectorcraft_engine::UiRequest::Place(p) = r { + crate::place::place_from_cursor(&mut app, &p); + } + } + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the clicked file asks"); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn scripted_places_and_places_that_give_layers_dont_ask() { + let b64 = vectorcraft_format::base64_encode(&layered()); + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // `file.place` run as a command places at once, as before. + let r = crate::place::run(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(r["format"], "psd"); + // The user's place with `layers` given doesn't ask either. + crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "layers": false})).unwrap(); + assert!(app.ui.dialog.is_none()); + } +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 377df81a72..8a59c7e567 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -682,14 +682,22 @@ const MESSAGE_DEPTH: usize = 5; /// Translate a status or error message for display (see the module docs). Unknown messages, and /// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as /// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”` or backticks, such as a -/// symbol's name), stay as they are. A part that starts with `{` or `[` is translated only -/// when it is a whole message with an exact entry, such as `[x, y] (two numbers)`. +/// symbol's name), stay as they are. A part that starts with `{` is translated only when it is a +/// whole message with an exact entry. A part that starts with `[` is translated when it has an +/// exact entry, such as `[x, y] (two numbers)`, or when it fits a template that starts with `[` +/// and an index of digits, such as an effect's refusal ``[0] `id`: {why}``. pub fn message(lang: Lang, s: &str) -> String { message_at(lang, s, MESSAGE_DEPTH) } fn message_at(lang: Lang, s: &str, depth: usize) -> String { - let Some((forms, caps)) = lang.catalog().message_forms(s) else { return s.to_string() }; + fill_message(lang, s, lang.catalog().message_forms(s), depth) +} + +/// `s` shown through the catalog entry `found` matched for it, its placeholder values translated +/// in turn while `depth` lasts. +fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures<'_, '_>)>, depth: usize) -> String { + let Some((forms, caps)) = found else { return s.to_string() }; let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::().ok()); let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); let Some(template) = forms.get(form) else { return s.to_string() }; @@ -697,8 +705,10 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { let nested = |v: &str| { if depth <= 1 || quoted(v) { v.to_string() - } else if v.starts_with(['{', '[']) { + } else if v.starts_with('{') { exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string()) + } else if v.starts_with('[') { + fill_message(lang, v, lang.catalog().indexed_message_forms(v), depth - 1) } else { message_at(lang, v, depth - 1) } diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index 6e112eb4f5..cbb2c5b702 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -262,6 +262,28 @@ impl Catalog { self.templates.iter().find_map(|t| t.captures(s).map(|caps| (t.forms.as_slice(), caps))) } + /// [`Catalog::message_forms`] for a part of a message that starts with `[`, which may be a JSON + /// array: an exact `@msg` entry, else only a template that starts with a literal `[` and a + /// placeholder whose value is an index of ASCII digits, such as ``[{j}] `{_1}`: {why}``. An + /// array such as ``["] `x`: b"]`` fits that template's text, but not its index. + pub fn indexed_message_forms<'a>(&self, s: &'a str) -> Option<(&[String], Captures<'_, 'a>)> { + if let Some(tr) = self.messages.get(s) { + return Some((std::slice::from_ref(tr), Vec::new())); + } + if s.len() > MAX_MESSAGE_LEN { + return None; + } + self.templates.iter().find_map(|t| { + let [Piece::Text(open), Piece::Hole(index), ..] = t.pieces.as_slice() else { return None }; + if open != "[" { + return None; + } + let caps = t.captures(s)?; + let digits = caps.iter().any(|(k, v)| k == index && v.bytes().all(|b| b.is_ascii_digit())); + digits.then_some((t.forms.as_slice(), caps)) + }) + } + /// The translation of a status or error message that has an exact `@msg` entry, as written in /// the catalog (`{{` and `}}` for literal braces); templates are not tried. pub fn exact_message(&self, s: &str) -> Option<&str> { diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index da5a12db2d..0ae36e3699 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5414,6 +5414,7 @@ imageTrace Outline Kontur @msg plug-in failed: {0} plug-in fejlede: {0} @msg plug-in manifest: {0} plug-in-manifest: {0} @msg plug-in output: {0} plug-in-output: {0} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} @msg plug-in parameters: {0} plug-in-parametre: {0} @msg plug-in trapped: {0} plug-in'et blev fanget: {0} @msg print settings are not an object printindstillingerne er ikke et objekt diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 07fdb5afe7..2864881e87 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7803,17 +7803,6 @@ imageTrace Outline კონტური @msg `name` must be the name of a script engine `name` უნდა იყოს სკრიპტის ძრავის სახელი @msg the main script engine is new for each run and is never kept, so it cannot be dropped მთავარი სკრიპტის ძრავა ყოველი გაშვებისთვის ახალია და არასოდეს ინახება, ამიტომ მისი მოცილება შეუძლებელია @msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს -@msg `answers` must be a list of answers `answers` უნდა იყოს პასუხების სია -@msg `answers` has more than {MAX_ANSWERS} answers `answers`-ში {MAX_ANSWERS}-ზე მეტი პასუხია -@msg `answers` is larger than 1 MiB `answers` 1 MiB-ზე დიდია -@msg `answers[{i}]` {e} `answers[{i}]`: {e} -@msg must be an object with `kind` and `value` უნდა იყოს ობიექტი `kind`-ითა და `value`-ით -@msg must have exactly `kind` and `value` უნდა ჰქონდეს ზუსტად `kind` და `value` -@msg is an alert's answer, whose `value` must be "ok" alert-ის პასუხია, ამიტომ მისი `value` უნდა იყოს "ok" -@msg is a confirm's answer, whose `value` must be true or false confirm-ის პასუხია, ამიტომ მისი `value` უნდა იყოს true ან false -@msg is longer than 16 KiB 16 KiB-ზე გრძელია -@msg is a prompt's answer, whose `value` must be a string or null prompt-ის პასუხია, ამიტომ მისი `value` უნდა იყოს სტრიქონი ან null -@msg must have `kind` alert, confirm or prompt `kind` უნდა იყოს alert, confirm ან prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` მხოლოდ ისეთი გაშვებისთვისაა, სადაც შესაკითხი არავინაა: აპში თითოეულ დიალოგს ადამიანი პასუხობს @msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index d509f0cc69..b632e5cac3 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -4089,7 +4089,8 @@ fn bracketed_message_parts_translate_only_as_exact_messages() { let point = message(lang, "[x, y] (two numbers)"); assert_ne!(point, "[x, y] (two numbers)", "{code}"); assert!(point.contains("[x, y]"), "{code}: {point}"); - for got in ["[1]", "[1, 2, 3]", r#"{"objects": [1]}"#, r#"[{"a": 1}, "b: c", …"#] { + // ``["] `x`: b"]`` fits the text of the effect refusal ``[{j}] `{_1}`: {why}`` but not its index. + for got in ["[1]", "[1, 2, 3]", r#"{"objects": [1]}"#, r#"[{"a": 1}, "b: c", …"#, r#"["] `x`: b"]"#] { let shown = message(lang, &format!("`center` must be [x, y] (two numbers), not {got}")); assert!(shown.contains(&point) && shown.contains(got), "{code}: {shown}"); let shown = message(lang, &format!("`p` must be an object, not {got}")); @@ -4098,6 +4099,42 @@ fn bracketed_message_parts_translate_only_as_exact_messages() { } } +/// An effect refusal inside another message (`plug-in output: …`, and an importer's `can't open …`) +/// is translated through its template with its reason, keeping the index and the effect id. +#[test] +fn nested_effect_refusals_translate_with_their_reason() { + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let refusal = "[0] `fx`: nothing selected"; + let output = format!("plug-in output: objects[0].effects: {refusal}"); + for shown in [message(lang, refusal), message(lang, &output), message(lang, &format!("can't open `a.svg`: {output}"))] { + assert!(!shown.contains("nothing selected") && shown.contains("[0] `fx`"), "{code}: {shown}"); + } + } + let de = de(); + let refusal = "[0] `fx`: `radius` must be a number"; + assert_eq!(message(de, refusal), "[0] `fx`: `radius` muss eine Zahl sein"); + let output = format!("plug-in output: objects[0].effects: {refusal}"); + assert_eq!(message(de, &output), "Plug-in-Ausgabe: objects[0].effects: [0] `fx`: `radius` muss eine Zahl sein"); + assert_eq!( + message(de, &format!("can't open `a.svg`: {output}")), + "`a.svg` kann nicht geöffnet werden: Plug-in-Ausgabe: objects[0].effects: [0] `fx`: `radius` muss eine Zahl sein" + ); + assert_eq!( + message(de, "plug-in output: objects[12].effects: [3] `fx`: no row for this reason"), + "Plug-in-Ausgabe: objects[12].effects: [3] `fx`: no row for this reason" + ); + let selected = "[1] `fx`: nothing selected"; + assert_eq!( + message(de, &format!("plug-in output: objects[0].effects: {selected}")), + "Plug-in-Ausgabe: objects[0].effects: [1] `fx`: nichts ausgewählt" + ); + // Past the depth limit the refusal stays as it is. + let deep = format!("plug-in output: plug-in output: plug-in output: plug-in output: objects[0].effects: {selected}"); + let shown = message(de, &deep); + assert!(shown.ends_with(selected), "{shown}"); +} + /// The warning for a PDF/X file that leaves out the document's bleed is translated in every catalog, /// alone and in the status bar's note. #[test] diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index e0e4e4c404..11c02ca139 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -52,10 +52,12 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt let load = if swatches { crate::panels::swatches::load_library } else { crate::panels::graphic_styles::load_library }; return load(app, p).map(|_| Value::Null); } - // A PDF with several pages or a password asks first (the Import PDF dialog), and so does a - // DXF drawing (DXF Import Options). + // A PDF with several pages or a password asks first (the Import PDF dialog), and so do a DXF + // drawing (DXF Import Options) and a PSD file with several layers or with slices (PSD Import + // Options), unless `p` says how its layers come in. if crate::dialogs::import_pdf::offer(app, name, bytes, path.clone(), None) || crate::dialogs::dxf_import::offer(app, name, bytes, path.clone(), None) + || (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, name, bytes, path.clone(), None)) { return Ok(Value::Null); } @@ -552,9 +554,11 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va check_import_size(path, false)?; let mut bytes = read(app, path)?; if background && opens_as(path).is_none() { - // A PDF with several pages or a password, or a DXF drawing, asks first, as at once. + // A PDF with several pages or a password, a DXF drawing, or a PSD file with several layers + // or with slices asks first, as at once. if crate::dialogs::import_pdf::offer(app, path, &bytes, Some(path.to_string()), None) || crate::dialogs::dxf_import::offer(app, path, &bytes, Some(path.to_string()), None) + || (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, path, &bytes, Some(path.to_string()), None)) { note_recent(app, path); return Ok(Value::Null); diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 5e4f5930f7..80c2464f62 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -61,7 +61,7 @@ pub fn is_document(name: &str) -> bool { #[derive(Default)] pub struct PlaceState { /// Web: the bytes of the files picked for the Place dialog, by name. - picked: Vec<(String, Vec)>, + pub(crate) picked: Vec<(String, Vec)>, /// The loaded cursor's thumbnails by file name. thumbs: Vec<(String, Thumb)>, /// The Control bar's `image.info`, for (document uid, revision, image id). @@ -125,10 +125,11 @@ fn engine(app: &mut VectorcraftApp, id: &str, p: &Value) -> Result Result { place_file(app, p, Read::AtOnce) } @@ -181,6 +182,7 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result Result Result = many.iter().filter(|s| s.get("path").is_none()).collect(); let mut q = json!({ "paths": paths, "files": files, "link": link, "template": template }); if !ask { - // Each text file and DXF drawing in the cursor takes the options confirmed last. + // Each text file, DXF drawing and embedded PSD file in the cursor takes the options + // confirmed last. q["text"] = crate::dialogs::text_import::last_options(app); q["dxf"] = crate::dialogs::dxf_import::remembered(app); + if !link || paths.is_empty() { + // Files from bytes have no file to link to; they may carry the dialog's Link. + q["link"] = json!(false); + crate::dialogs::psd_import::queue_options(app, &mut q); + } } queue_files(app, &q, Read::ForUser { dropped: false }, ask) } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 4fd56c72fb..26d3753b51 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -831,6 +831,9 @@ pub struct UiState { /// never used). #[serde(default)] pub dxf_import: Value, + /// The PSD Import Options chosen last (layers, hiddenLayers, importSlices; null: never used). + #[serde(default)] + pub psd_import: Value, /// The Home screen is shown over the open documents (`app.home`): the active document's uid /// and the document count when it opened. Choosing a tab, or a document opening, closing or /// becoming active, leaves it. @@ -1260,6 +1263,7 @@ impl Default for UiState { transform_each: Value::Null, rearrange_artboards_spacing: Value::Null, dxf_import: Value::Null, + psd_import: Value::Null, home: None, trace_hold_source: None, layers_panel: Default::default(), diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d52720f29e..b0bd90eb59 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol -> **Last updated:** 2026-11-07 · **Change:** text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). +> **Last updated:** 2026-11-15 · **Change:** completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). `vectorcraft --control ` listens on `127.0.0.1:` (loopback only). The port must be a number from 1 to 65535 (`--control=` works too), given once; otherwise the app prints an error and exits @@ -105,8 +105,8 @@ the two can still win that race. | `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section` and `__allArtboards` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass, Texturizer and Rough Pastels effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | -| `ui.render` | `{path?, scale?, artboard?, data?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | -| `ui.resize` / `ui.focus` | | | +| `ui.resize` | `{width?, height?}` | request the window's inner size; omitted or null `width` and `height` default to 1440 and 900. Returns `null` | +| `ui.focus` | `{}` | request keyboard focus for the window. Returns `null` | | `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`), after a line about the document's linked files when there is one (Missing linked files below), counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). It accepts a key that only another format takes and does not use it: the reply's `warnings` and the status bar name the key ("`quality` was not used: PDF files don't read it"). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | @@ -1137,6 +1137,7 @@ hidden tab (whose frames the browser pauses) answers when it is shown again. | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | Completed the `ui.resize` defaults and `ui.focus` contract; kept one `ui.render` entry, including `traceViews`. Documentation only. | | 2026-11-07 | minor | Documented OpenType feature values in text commands (`"salt=2"`, the font's alternate number) and that runs differing only in features shape as one piece of text. | | 2026-10-31 | minor | Confining file access: on Windows a `:` in a name after the drive (an NTFS alternate data stream) is refused with the device names (#3604). | | 2026-10-25 | minor | Panel docking on craft-ui's layout: `ui.docking`, the floating and dock parameters, native floating windows. | diff --git a/docs/development.md b/docs/development.md index 7c22d6ae98..100786bb83 100644 --- a/docs/development.md +++ b/docs/development.md @@ -294,7 +294,10 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE control channel, MCP and tests read them) and are translated only where the status bar draws them (`i18n::msg`). `@msg` catalog rows hold a whole message or a template such as `Couldn't open {name}: {e}`; `{_1}`, `{_2}` … stand for the format string's `{}`, and the values in the - placeholders are translated in turn (the reason after `: {e}` is often a message too). A literal brace in a + placeholders are translated in turn (the reason after `: {e}` is often a message too). A value that starts with + `{` is translated only when it has an exact row, so a JSON object stays as it is; a value that starts with `[` is + also matched against a template that starts with `[` and an index of digits, such as an effect's refusal + ``[{j}] `{_1}`: {why}``, so its reason is translated while a JSON array stays as it is. A literal brace in a row is written `{{` or `}}`, in the English and in the translation: a message made with `format!` keeps the doubled braces of its format string, and a plain string literal has each of its braces doubled, so the row for `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch and Danish diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 207cf5bc1b..7a73bdc4c1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -294,7 +294,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | -| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | placing as layers and a PSD import options dialog missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | +| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | | WebP | export (Export for Screens) | yes | yes (lossless only; lossy written lossless with a warning) | | diff --git a/docs/mcp.md b/docs/mcp.md index 57c349d335..d7e47925ed 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7194,10 +7194,12 @@ with `pointer_gesture` (a click places at 100% with the top-left corner there, a number, naming the key, and place nothing; null is the same as leaving the key out. In the app, `file.place` asks for a file's import options before placing it: a text file without `text` (Text Import -Options), a DXF drawing without `dxf` (DXF Import Options), and a PDF, `.ai` or `.ait` file with several pages or a -password and no `page` (Place PDF). `showImportOptions: false` places such a file without asking, with the options -last confirmed in its dialog: the text options, and the DXF fit, lineweight, centering and layer choices with the -drawing at 1:1 in its own unit. A PDF is placed on page 1 (or `page`) and its crop box, and an encrypted PDF given no +Options), a DXF drawing without `dxf` (DXF Import Options), a PDF, `.ai` or `.ait` file with several pages or a +password and no `page` (Place PDF), and a PSD or PSB file embedded without `layers` that has two layers or more or +slices (Place PSD). `showImportOptions: false` places such a file without asking, with the options last confirmed in +its dialog: the text options, the DXF fit, lineweight, centering and layer choices with the drawing at 1:1 in its own +unit, and the PSD conversion, hidden-layer and Import Slices choices. A PDF is placed on page 1 (or `page`) and its +crop box, and an encrypted PDF given no `password` still asks for the password. A `showImportOptions` that is not true or false is refused, and nothing is placed. The Place dialog (File › Place, or `file.place {paths}`) has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). @@ -8626,6 +8628,65 @@ flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, R A document with transparency keeps it. `file.place {path}` links the file like any image (`links.update` reads it again when it changes); Multichannel files are refused. +`file.place` with `layers: true` embeds a PSD or PSB file's layers as objects instead, and `hiddenLayers: true` +brings the hidden layers in, hidden. The +[PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) +offer the conversion and the hidden layers only for a file that is opened or embedded, and a linked file shows its +flat image. The rest are VectorCraft's own rules: + +- The layers are read as `document.open` reads them (below) and placed as one group named after the file. A layer + becomes an image and a layer group becomes a group, each with the layer's name, visibility, opacity, blend mode + and opacity mask. A Pass Through group is not isolated; a group in any other mode is. +- The group takes the place the merged image would take: `at` centers the file's canvas and `rect` fits it. When + layers reach past the canvas, hidden layers included, the group is a clip group whose clipping path is the canvas. +- The layers are never linked. With `layers: true`, `link` is false unless it is given, and `link: true` is an + error. +- `hiddenLayers: true` without `layers: true` is an error. +- A file without layers is embedded as its merged image, and so is a file whose layers are all left out, with the + import's warnings. A file whose layers can't be read is embedded as its merged image with a warning. +- `file.place.queue` and `file.place.info` take `layers` and `hiddenLayers` too. + +`document.psdInfo` reads a PSD or PSB file without opening it: its `format` (`psd` or `psb`), the canvas `width` +and `height` in pixels, and the counts `layers` (group markers left out), `hiddenLayers`, `groups` and `slices` +(the slices `importSlices` brings in). A file without layer records, or whose layer records can't be read, has +`layers: 0`; a file without slices, or whose slices can't be read, has `slices: 0`. A file that is not a PSD or PSB +file is an error. + +`importSlices` brings a PSD or PSB file's slices in as user slices (Object › Slice), which Save for Web exports. +The [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) +keep the slices a file holds, and offer it only for a file that is opened or embedded. The slices are read from +image resource 1050 as the +[Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it, +in version 6 and in the descriptor of versions 7 and 8. The rest are VectorCraft's own rules: + +- `document.open` takes `importSlices`, default true, with the layers as objects and with `layers: false` alike. + The slices lie over the canvas, each clipped to it. +- `file.place` takes `importSlices`, default true when the file is embedded and false when it is linked; + `importSlices: true` with a linked file is an error. The slices move and scale with the placed art, in the same + undo step, and the reply lists their ids in `slices`. `file.place.info` counts them in `slices`, and + `file.place.queue` takes `importSlices` too. +- Each slice keeps its name, its type (Image or No Image), its link, target, message, alternative text and + background color, and a No Image slice keeps its cell text (plain text escaped as HTML). Text alignment isn't + read. A slice that follows a layer comes in as a user slice over the rectangle the file stores for it. +- Slices the file generated automatically are left out: the document lays out its own auto slices around the + others. A slice wholly outside the canvas, or without a size, is left out with a warning, and so are slices that + can't be read; the file's art comes in either way. A file without slices brings no warning. + +In the app, File › Open of a PSD or PSB file with two or more layers, or with slices, shows PSD Import Options: +Convert Layers to Objects (with Import Hidden Layers) or Flatten Layers to a Single Image, and Import Slices, which +is offered only for a file with slices and applies to either choice. File › Place shows the same dialog for such a +file placed without Link, and so does a file dropped on the canvas with Shift held. The dialog starts from the +choices made last, at first Convert Layers to Objects without hidden layers, with Import Slices. A file with fewer +than two layers and no slices, a file placed with Link, and `document.open` and `file.place` run as commands don't +show it. Several files placed together without Link load the place cursor without asking, and each PSD or PSB file +among them comes in with the choices made last. + +```json +{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/poster.psd","layers":true,"hiddenLayers":true}}} +{"name":"run_command","arguments":{"command":"document.psdInfo","params":{"path":"/tmp/poster.psd"}}} +{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","importSlices":false}}} +``` + A PSD or PSB file that names a clipping path (the saved path its clipping path resource names, in the [published PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)) places, and opens as its merged image (`layers: false`, a file with no layers, or a file whose layers can't be read), inside a clip group whose clipping @@ -8685,8 +8746,7 @@ Each layer's pixels must fit the memory allowed for one image, and the pixels of canvases the merges make, must together fit eight times that; a file past either limit opens as its merged image, with a warning. The canvases one step of a merge holds at once must also fit the memory allowed for one image; when they don't, the layer that needed the merge comes in alone, with a warning: in the Normal mode, or as a layer of its -own instead of clipped. File › Open in the app has no PSD import options dialog: it converts the layers and leaves -hidden layers out. +own instead of clipped. ```json {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","hiddenLayers":true}}} @@ -9390,7 +9450,7 @@ a pair. The setting works only with a Kinsoku Set: with Kinsoku Set None the par and the menu item is unavailable. Off by default, for new type and for paragraphs saved before the option. It is saved with the paragraph (`bunri_kinshi` in `para`) only when on, paragraph styles carry it (Paragraph Style Options › East Asian Composition Settings), and Reset Panel turns it off. A value that is not true or false is refused. One undo -step. `.ai` editing data does not hold it, and a save reports a paragraph with it on and a pair in it as left out. The help page: +step. An `.ai` save writes it with each paragraph, under Kinsoku Set None too, and it reopens as set. The help page: https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 85d4412e45..4f7a0fe2e5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -592,6 +592,7 @@ since 2026-10-01. - 3D lighting widget: the Lighting tab of the 3D and Materials panel shows every light on a sphere at its Rotation and Height; a drag moves a light in one undo step, a press selects it, Move Light to Back and Move Light to Front change its side, and the arrow keys move the focused light ([three-d.md](three-d.md#lighting-widget)). `crates/ui-egui/src/panels/tests_three_d.rs` covers the drag, selection, side and keyboard. - 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance. Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. Softness and the shadows of lights after the first are not built. Scores unchanged. - 3D shadows: with Shadows on, Revolve, Extrude & Bevel, Inflate and Rotate cast the shadow from the faces kept by the build that draws each solid, so drawing an object builds each of its solids once. The art and the shadow are unchanged. Evidence: `crates/three-d/src/shadow/tests.rs` (`a_solid_and_its_shadow_are_built_once` and the tests that compare each solid and its shadow with the two built apart), `solids::tests_shadow::a_shadowed_3d_object_builds_each_solid_once`, `solids::tests_shadow::the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it`, `revolve::tests::the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it`. Scores unchanged. +- 3D shadows: in Revolve, Extrude & Bevel, Inflate and Rotate, a fill, stroke or member whose opacity is NaN or infinite casts no part of the shadow, as one at 0 % does, whether the shadow is cast from the solids drawn or from solids built for it alone; the art beside it still casts. This is VectorCraft's own rule. Evidence: `solids::tests_shadow::art_whose_opacity_is_not_a_finite_number_casts_no_shadow`, `revolve::tests::a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow`. Scores unchanged. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. @@ -994,6 +995,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The errors of the parameter checks that many commands share show in the status bar in the interface language: a value that is not a number where a number goes (`object.move` with `"dx": "60 mm"`, and `object.rotate`, `object.setBounds` and the other commands that call `check_numbers`), a missing number or index, `ids` that are not a list of object ids, an object id that is not a non-negative integer or names no object, and a date that is not Unix seconds. Each has a row in every catalog that translates all status and error messages, and in Bulgarian, Danish, Indonesian and Dutch (`shared_param_check_errors_are_translated`). - File Info's (`file.info`) error for a value with control characters shows in the status bar in the interface language for every field: "description has control characters" for Description and Copyright Notice, which take line breaks and tabs, and "title has control characters or line breaks" for the other text fields and each keyword in a list. Each is its own message with a row in every catalog that translates all status and error messages, and the field's key stays as written (`file_info_control_character_refusals_translate_in_every_complete_catalog`, `control_characters_are_refused_with_the_field_rule`). - A parameter schema's errors show in the status bar with what the value must be in the interface language, for every type a schema has (a number with each kind of range and with a unit, an integer and its range, true or false, a string, a list of names, an object id, a list of object ids, a color, a point, an object and a list), in every catalog that translates all status and error messages; the path, the refused value, the bounds, the unit and the names stay as the English gives them. The error for a value that is not one of its names is also translated in Bulgarian, Bosnian, Danish, Indonesian and Dutch (`parameter_schema_expected_phrases_are_translated`, `bracketed_message_parts_translate_only_as_exact_messages`). + - An effect a plug-in's output or an importer plug-in's objects carry that VectorCraft refuses (``[0] `id`: reason``) shows in the status bar with its reason in the interface language inside `plug-in output: …` and `can't open …`, in every catalog that translates all status and error messages; the index and the effect id stay as they are, and a JSON array in a message stays as it is (`nested_effect_refusals_translate_with_their_reason`, `bracketed_message_parts_translate_only_as_exact_messages`). - The untranslated report lists the status and error messages of the effects, swatch libraries, raster sizes and encoders, 3D solids and path operations that a catalog lacks, the messages that a `.map_err` closure or a named error handler returns, and the phrases a parameter schema's error builds for what a value must be (`untranslated_report_checks_every_message_crate_and_schema_phrase`, `message_scan_reads_map_err_closures`, `message_scan_reads_named_map_err_handlers`). - Spanish messages (2026-11-13): the Spanish catalog (`crates/ui-egui/src/i18n/es.tsv`) has an `@msg` row for 114 of the 167 status and error messages that the untranslated report (`untranslated_report`) lists as missing in all 23 complete-message languages: the errors of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and the parameter checks. Open #7211 and #7378 translate 51 of the others (the composite font and SVG filter errors), and 2 stay in English. The rows keep the placeholders, backticked names, accepted values and limits of their English (`spanish_translates_encoder_profile_swatch_revolve_and_parameter_errors`); native review remains; scores and estimates unchanged. - Export commands run through MCP, the control channel or the CLI refuse a key that no format takes, and warn about a key that only another format takes (`{"format": "pdf", "quality": 80}` writes the PDF with the warning "`quality` was not used: PDF files don't read it"; `an_option_only_another_format_reads_gets_a_note`, `control_export_notes_an_option_the_format_does_not_read`, `convert_warns_about_an_unused_option_only_when_one_was_given`), and a command that writes one format (`document.exportPdf`, `document.exportEps`, `document.exportDxf`) or takes one format's options (`document.pdfSettings`, `pdf.preset.save`) refuses a key that format doesn't take. An unknown key inside `marks`, `bleed`, `compression`, `output`, `advanced`, `security` or `flattener` is refused by its path. @@ -1458,7 +1460,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type on a path with right-to-left text that does not fit shows the longest start of its text whose glyphs fit, also where tracking gives a letter a negative advance and a shorter start does not fit; the rest overflows or flows to the next threaded object (VectorCraft's own rule). Without hanging punctuation, and on a straight path or with no spacing, every start is measured without arranging it on the path again. With hanging punctuation, or spacing on a curve, when a letter has a negative advance, at most 32 of the starts that could fit are arranged one by one from the longest; when none of them fits, a binary search over the rest shows a start that fits, which is not always the longest (`overflowing_rtl_type_on_a_path_shows_the_longest_start_that_fits`, `the_longest_rtl_start_on_a_path_is_found_without_arranging_each_start`, `the_longest_rtl_start_on_a_path_is_the_one_each_start_gives` and `rtl_type_on_a_curve_whose_letters_take_the_line_back_is_arranged_a_bounded_number_of_times` in `crates/text/src/tests/bidi.rs`). Right-aligned and centered type on a curve with Spacing is placed by what its glyphs take where the line ends up, so text that fits is not cut off at the end bracket (`on_path_aligned_spaced_text_that_fits_shows_whole` in `crates/text/src/tests.rs`). The Paragraph panel menu's Kinsoku Shori Type (`text.setFormat {kinsokuType}`, with the East Asian options) picks Push In First, Push Out First or Push Out Only for each paragraph: a character the Kinsoku Set keeps off a line's start or end is set on the line, with the line's gaps next to CJK characters closed by at most a tenth of an em each to fit, or moved to the next line with the character before it. Push Out First pushes in only when pushing out would leave the line more than an em short. Push Out Only is the default, the setting is saved only when it is not, and paragraph styles carry it. The Paragraph panel menu's Bunri-Kinshi (`text.setFormat {bunriKinshi}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) keeps inseparable pairs on one line in each paragraph that has it: two em dashes, two ellipses, two two-dot leaders and the two halves of a vertical kana repeat mark (the pairs of W3C JLREQ's class cl-08, VectorCraft's set). Both composers and vertical type follow it, and justification adds no space inside a pair. It works with a Kinsoku Set only, is off by default and is saved only when on; editing the set of pairs is not available. - `.ai` import reads each paragraph's Kinsoku Set (None, Hard or Soft), Kinsoku Shori Type, Burasagari and Bunri-Kinshi from the file's editable text: the paragraph's own setting, else its paragraph style's or a style that one is based on, else the document's default. A paragraph with a custom Kinsoku set takes its paragraph style's set, and the importer warns about it. A value it cannot read takes its paragraph style's value too. `.ai` export does not write these settings. + `.ai` import reads each paragraph's Kinsoku Set (None, Hard or Soft), Kinsoku Shori Type, Burasagari and Bunri-Kinshi from the file's editable text: the paragraph's own setting, else its paragraph style's or a style that one is based on, else the document's default. A paragraph with a custom Kinsoku set takes its paragraph style's set, and the importer warns about it. A value it cannot read takes its paragraph style's value too. An `.ai` save writes all four settings for every paragraph, the normal paragraph style and the document's defaults, and lists the Hard and Soft sets, in the form that reader reads, so they reopen as set and are not reported as left out; Burasagari and Bunri-Kinshi keep their values under Kinsoku None. The Paragraph panel menu's Korean Line Break Anywhere (`text.setFormat {koreanLineBreakAnywhere}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) sets for each paragraph whether a line may break between any two Hangul syllables. When it is off, a word that contains Hangul breaks only at its spaces and after punctuation, or where the word is wider than the line, and takes no hyphen. New type has it off; paragraphs saved before the option read as on, so their lines do not move. The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo step. The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. @@ -1702,6 +1704,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. PDF export writes a knockout group as one PDF knockout group (`/K true`, with `/I true` when the group isolates; ISO 32000-1, 11.4.6.3), so a knockout group of any size opens again in VectorCraft as a knockout group, and the form nesting of the file does not grow with the number of elements. When an element's opacity or mask defines its knockout shape, or it paints translucently, each element is drawn through one soft mask of the overlapping elements above it instead; past 65,536 objects in a group's masks (or 2,048 elements) the group is a PDF knockout group, with a warning that its translucent elements knock out fully. SVG export draws each element of a knockout group through one mask of the overlapping elements above it, and the masks refer to one copy of each element's shape, so the elements stay siblings and the file nests no deeper with more elements; past 65,536 shapes in a group's masks (or 2,048 elements) the group is written as a plain group, with a warning. Evidence: `pdf/src/tests/blend.rs`, `svg/tests/it/blend_export.rs`, `pdf/tests/gradient_forms.rs` (a gradient in a knockout group reads back in place). + A knockout group in Normal mode at full opacity that does not isolate, with nothing blending inside, is written without an isolated group around its elements, clipped or not, so the art below the group is its initial backdrop in the PDF as on the canvas (ISO 32000-1, 11.4.5): neither its `/K` group nor a form around a clipped group carries `/I true`, and an overprinting element in it overprints the art below the group. Evidence: `pdf/src/tests/blend.rs` (`a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates`, `an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below`). - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eleven generated style libraries (including Game HUD, Status Effects, Neon & Glow, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, and Textures) save and load as `.vcstyles`. The built-in Textures graphic style library (`graphicStyle.addFromLibrary {library: "textures"}`) has eight styles that paint their fills and strokes with the texture effects: Fine Grain (Grain), Canvas Weave and Burlap Sack (Texturizer), Cracked Glaze (Craquelure), Mosaic Floor (Mosaic Tiles), Quilted Squares (Patchwork), Leaded Glass (Stained Glass) and Damp Paper (Water Paper). The help page names new graphic styles for textures ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html)) without naming them, so the styles, their names and their settings are VectorCraft's own (`tests::stylelib::textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open`). In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. @@ -1800,6 +1803,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps the document's variables, data sets and the bindings of objects to variables in its editing copy, in the form the variable library reader above reads, so they come back when the file is opened. Bindings to layers, to type written as outlines, to graphs and to linked images written as other objects, data set values of graphs, and variables, data sets, bindings and values past the writer's limits are left out with a warning (#6024; `crates/eps/src/ai_editing/tests.rs` `variables_data_sets_and_bindings_are_read_back`; `crates/eps/src/ai_editing/writer/variables.rs` lists what is left out). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps each wrap object's Text Wrap Options in its editing copy: the Offset, positive or negative, and Invert Wrap ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/wrap-or-unwrap-text-around-objects.html)), in the form the `.ai` reader reads them (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so they come back when the file is opened. An offset past the -1000 to 1000 pt the reader keeps is written as the nearer end of that range. On a large canvas the offset is written at the art's scale and comes back at its size. Art the writer draws for an object, such as a blend's steps or a symbol instance written as its art, has only that object's options, and a clipping path written as its fills and its strokes has its options once (`crates/eps/src/ai_editing/tests.rs` `text_wrap_options_are_written_and_read_back`, `drawn_art_keeps_only_its_objects_text_wrap`, `text_wrap_offsets_on_a_large_canvas_come_back_at_their_size`, `text_wrap_options_of_type_and_envelopes_are_read_back`, `a_clipping_path_written_as_its_paint_keeps_one_text_wrap`). Type written as its outlines in the editing copy still wraps area type by its bounds, not by its glyphs, when the file is opened: the outlines' group ends with an unpainted rectangle at the type's bounds that carries its Text Wrap Options, in the form the `.ai` reader reads a path's options (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), and the group keeps the type's name (`crates/eps/src/ai_editing/tests.rs` `type_written_as_outlines_keeps_wrapping_by_its_bounds`). + A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). @@ -1838,6 +1842,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws; where they don't, even with the drawn art of every live envelope put back, and are used all the same, trusted, with the objects that differ coming in as the page's art, or opened alone, it stays live where, in the pixels it and its drawn art ink (drawn together without the rest of the layers), the layers with it differ from the page in no more than its own check allows and the envelopes that stay differ there in no more than half of what the page check allows, and nothing above it clips, masks or moves it); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; after those tries (and before a grid moved onto its drawn art), it is also tried mapped from the box of what it paints, where that is another box, as users' files map some such type: its glyph outlines with their fills and strokes baked as the envelope bakes them, so geometry effects on them count (a stroke a Transform effect moves paints where it is moved to), each measured by its visual bounds (exact for miter joins, a tip counting where the miter limit keeps it, and for round joins; an upper bound for bevel joins, miters the limit cuts, width profiles and square-capped dashes), and a contour of zero length, which paints nothing, left out; effects on the type object itself are left out, as VectorCraft applies them after the envelope bends the type. The drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. The drawn art of these files strokes type in an envelope along its bent outlines at the stroke's own weight, Distort Appearance on or off, and VectorCraft draws it so (#6644): an envelope of stroked type whose grid squeezes or stretches it opens live where it draws as that art. + In a `.ai` opened from its editing data, an envelope in another envelope's contents opens as a live envelope inside the live outer one, with Edit Contents on or off at either level, also where its record lies straight in the outer envelope's `AIDeformArtKey` block with no group around it; each level edits its own contents without removing its distortion, as the help page describes for one envelope (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html). Each envelope is compared with its own drawn art: an inner one that doesn't match keeps its drawn art as the outer envelope's contents, and an outer one that doesn't match keeps its own drawn art. An inner record left without its `XP` stops waiting when the outer dictionary ends, and an envelope in an opacity mask's art reads as part of the mask (`an_envelope_in_an_envelope_s_contents_opens_live_inside_it` and the tests after it in `crates/eps/src/import/ai/tests.rs`). In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). 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`, on by default; `.ai` saves leave it off) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard, so readers that ignore `UserUnit` show them at full size. @@ -1872,8 +1877,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels. There is no PSD import options dialog yet (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` keep the clip group, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). + - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`). - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. Each axis uses the valid display resolution (`resd`), else the valid capture resolution (`resc`), whichever box comes first ([ITU-T T.800](https://www.itu.int/rec/T-REC-T.800/en), I.5.3.7.2); an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`).