diff --git a/Cargo.lock b/Cargo.lock index e602203964..e495bad15e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6901,6 +6901,7 @@ dependencies = [ "cfb", "chrono", "craft-cdr", + "craft-codepage", "craft-docpath", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-jxl", @@ -7060,6 +7061,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ + "craft-codepage", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-metafile", "image", @@ -7200,6 +7202,7 @@ dependencies = [ "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-mime", "craft-svg", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "data-url", "flate2", "image", diff --git a/Cargo.toml b/Cargo.toml index 43d488a3f9..4bbd7d964d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,6 +48,7 @@ craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" } craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/apps/vectorcraft/src/window.rs b/apps/vectorcraft/src/window.rs index ce224584fd..e36add3d08 100644 --- a/apps/vectorcraft/src/window.rs +++ b/apps/vectorcraft/src/window.rs @@ -170,6 +170,12 @@ fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] { std::array::from_fn(|i| size[i].min(room[i]).max(MIN_SIZE[i].min(room[i])).max(1.0)) } +/// The smallest size a window of `size` points may take: [`MIN_SIZE`], lowered to `size` in each +/// dimension where [`fit`] made the window smaller than that to fit a small work area. +fn min_size(size: [f32; 2]) -> [f32; 2] { + std::array::from_fn(|i| MIN_SIZE[i].min(size[i])) +} + /// Whether to list the monitors again: on the first frame, when the UI zoom changed, and at most /// every [`MONITORS_EVERY`] seconds while the app draws. `listed` holds the last list's time and zoom. pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool { @@ -302,6 +308,12 @@ pub fn restore(window: &winit::window::Window, saved: Option) -> if let Some([x, y]) = g.pos { window.set_outer_position(PhysicalPosition::new(x, y)); } + // The native minimum (`MIN_SIZE`, set in `native_options`) would keep the window bigger than a + // size fitted to a small work area, so it is lowered to that size first. + let min = min_size(g.size); + if min != MIN_SIZE { + window.set_min_inner_size(Some(LogicalSize::new(min[0], min[1]))); + } // Returns the new size when it applies at once; either way the window gets it. let _ = window.request_inner_size(LogicalSize::new(g.size[0], g.size[1])); #[cfg(not(target_os = "linux"))] @@ -444,6 +456,21 @@ mod tests { assert_eq!(monitor(0, 0, 1920, 1080, 1.0).less_frame([16, 39]).work, None); } + #[test] + fn a_window_fitted_below_the_smallest_size_lowers_the_minimum_to_its_size() { + // 1366 × 768 at 150% with a 48-pixel taskbar along the bottom: a work area 480 points high. + let areas = [WorkArea { monitor: [0, 0, 1366, 768], work: [0, 0, 1366, 720] }]; + let m = [monitor(0, 0, 1366, 768, 1.5).with_work_area(&areas)]; + let g = place(saved(Some([0, 0]), [900.0, 500.0], false), &m, Some(0)); + assert_eq!(g.size, [900.0, 480.0]); + // The minimum height drops to the fitted 480 points; the width keeps the normal minimum. + assert_eq!(min_size(g.size), [800.0, 480.0]); + // A window with room for the smallest size keeps the normal minimum. + let big = [monitor(0, 0, 1920, 1080, 1.0)]; + assert_eq!(min_size(place(saved(Some([0, 0]), [1000.0, 700.0], false), &big, Some(0)).size), MIN_SIZE); + assert_eq!(min_size([1.0, 1.0]), [1.0, 1.0]); + } + #[test] fn macos_screen_rects_turn_into_winits_top_left_pixels() { // A 1512 × 982 point primary screen at 2× with a 37-point menu bar and an 80-point Dock, diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 608902756b..04a96c97fd 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -551,13 +551,19 @@ impl Document { } /// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes - /// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). + /// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). A + /// node that is or holds a dimension (a pasted one) sets [`Document::dimensions`]. pub fn insert(&mut self, parent: Option, index: usize, node: Node) -> Result { + fn holds_dimension(n: &Node) -> bool { + n.extras().dimension.is_some() || n.children().into_iter().flatten().any(|c| holds_dimension(c)) + } let id = node.id; self.check_ruler_guide_place(&node, parent)?; + let dimension = !self.dimensions && holds_dimension(&node); let ch = self.children_mut(parent)?; let i = Node::insert_index(ch, index, &node); ch.insert(i, Arc::new(node)); + self.dimensions |= dimension; Ok(id) } @@ -659,6 +665,21 @@ impl Document { Ok(()) } + /// Put each list of nodes in `items` directly below its anchor, in list order, in one pass over + /// the children of each parent. It fails as [`Document::insert_beside`] does. + pub fn insert_below(&mut self, items: Vec<(NodeId, Vec)>) -> Result<(), DocError> { + let anchors: Vec = items.iter().map(|(id, _)| *id).collect(); + let places = self.places(&anchors)?; + let mut lists: Vec> = items.into_iter().map(|(_, nodes)| nodes).collect(); + self.edit_children(places, |k, anchor, children| { + let nodes = lists.get_mut(k).map(std::mem::take).unwrap_or_default(); + children.extend(nodes.into_iter().map(Arc::new)); + children.push(anchor); + })?; + self.index.clear(); + Ok(()) + } + /// Where each of `ids` is ([`Places`]). Fails with `NoNode` for an id that is not in the tree, /// is listed twice or lies inside another listed node. fn places(&self, ids: &[NodeId]) -> Result { diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 7c0de44cab..fdd18c4693 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -115,6 +115,36 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } +/// Adds the geometry and raster effects of a symbol instance's active fill and stroke to the fills +/// and strokes that paint in the art it is given, the instance's art in the symbol's coordinates, +/// as the canvas adds them to the art it draws. Every object keeps its place in the art, so the +/// child indices of [`symbol_part_at`] still lead to it. Effects are evaluated above this crate, so +/// the engine registers one with [`set_instance_row_art`]. +pub type InstanceRowArt = fn(Option<&Document>, &Node, &mut Node); + +static INSTANCE_ROW_ART: OnceLock = OnceLock::new(); + +/// Register how a symbol instance's art takes the effects of the instance's fill and stroke, for +/// Direct Selection's parts (the first registration stays). +pub fn set_instance_row_art(f: InstanceRowArt) { + // Already set: the same engine, registered by another session. + let _ = INSTANCE_ROW_ART.set(f); +} + +/// Does a symbol instance's active fill or stroke carry a visible geometry effect, which the art it +/// places takes on each of its fills and strokes ([`set_instance_row_art`])? Effects are classified +/// above this crate, so the engine registers one with [`set_instance_reshapes`]. +pub type InstanceReshapes = fn(&Node) -> bool; + +static INSTANCE_RESHAPES: OnceLock = OnceLock::new(); + +/// Register how Direct Selection tells whether a symbol instance's fill or stroke effects reshape +/// its art (the first registration stays). +pub fn set_instance_reshapes(f: InstanceReshapes) { + // Already set: the same engine, registered by another session. + let _ = INSTANCE_RESHAPES.set(f); +} + /// The shapes that [`ImagePaint`] gives for one object. type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; @@ -1575,12 +1605,67 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio /// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a /// stroke along its shape, a fill inside it except with Selection by Path Only. fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { - image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { + painted_hit(&image_paint(Some(symbols.document()), n), p, opt) +} + +/// What a click at `p` hits among `painted`, the shapes [`image_paint`] gives, as [`hit_painted`] +/// tests them. +fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option { + painted.iter().rev().find_map(|(bp, rule, item)| match item { AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), }) } +/// Is `n` a symbol instance whose active fill or stroke has a visible geometry effect, which +/// reshapes the art it draws ([`set_instance_reshapes`])? This holds whatever that art is, clip +/// groups and type included. Callers ask [`own_effects_art`] first, which takes an instance whose +/// own effects change what it draws; an instance whose own effects add only pixels (a drop shadow) +/// is tested here. Never with `outline`, where the canvas draws no effects, nor while a +/// [`DrawnOff`] guard lives, nor while nothing is registered. +fn reshapes_instance_art(n: &Node, outline: bool) -> bool { + !outline + && !DRAWN_OFF.get() + && matches!(n.kind, NodeKind::SymbolInstance { .. }) + && n.appearance.items.iter().any(|i| !i.effects().is_empty()) + && INSTANCE_RESHAPES.get().is_some_and(|f| f(n)) +} + +/// How many objects `n` holds with its opacity masks' art ([`Node::count_with_masks`]), what +/// testing or outlining it takes from the [`ArtWalk`] limit. +fn walk_size(n: &Node) -> u64 { + u64::try_from(n.count_with_masks()).unwrap_or(u64::MAX) +} + +/// The art that symbol instance `n` draws with a visible effect of its own, the effects of its +/// fills and strokes and those of its symbol's art all applied, or that type `n` draws with the +/// visible effects of its own and of its fills and strokes, as outlined paths ([`set_drawn_art`]). +/// `None` for other objects, with `outline`, where the canvas draws no effects, for an instance or +/// type without such an effect, while a [`DrawnOff`] guard lives, and when no geometry effect +/// changes what it draws. Evaluating the art is work that walking it does not count, so the art +/// takes its objects from the [`ArtWalk`] limit of the click or outline under way, and the walk of +/// it takes them again. Once the limit is used up, the result is `Some` of an empty group, which +/// hits and outlines nothing, and no more art is evaluated. +fn own_effects_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> Option { + let has = match n.kind { + NodeKind::SymbolInstance { .. } => n.appearance.effects.iter().any(|e| e.visible), + NodeKind::Text(_) => has_own_effects(n), + _ => false, + }; + if outline || DRAWN_OFF.get() || !has || DRAWN_ART.get().is_none() { + return None; + } + let nothing = || Some(Node::group(n.id, vec![])); + if ArtWalk::used_up() { + return nothing(); + } + let art = DRAWN_ART.get()?(symbols, n)?; + if !ArtWalk::take(walk_size(&art)) { + return nothing(); + } + Some(art) +} + /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path /// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and /// type on a path's path, drawn through `n`'s perspective projection if it has one. @@ -1690,6 +1775,41 @@ impl<'a> InstanceArt<'a> { Some(Self { art, map, xf: *xf, boxes }) } + /// [`Self::of`] with the effects of the instance's active fill and stroke added to the fills and + /// strokes in the art ([`set_instance_row_art`]), so that each object of it is tested and + /// outlined where the canvas draws it. Not with `outline`, where the canvas draws no effects. + fn drawn(doc: &'a Document, inst: &Node, outline: bool) -> Option { + let mut art = Self::of(doc, inst)?; + #[cfg(test)] + ARTS_WALKED.with(|c| c.set(c.get() + 1)); + if !outline && let Some(f) = INSTANCE_ROW_ART.get() { + f(Some(doc), inst, &mut art.art); + } + Some(art) + } + + /// [`Self::drawn`] for symbol instance `inst` in the art of another instance, outside Outline. + /// Copying the art and adding the effects to it is work that walking it does not count, so the + /// art takes as many objects as placing it makes ([`Self::size`]) from the [`ArtWalk`] limit of + /// the click or outline under way before it is copied, as the marquee takes the art it places, + /// and the walk of it takes its objects again. `None` once fewer are left. + fn nested(doc: &'a Document, inst: &Node) -> Option { + if ArtWalk::used_up() { + return None; + } + let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; + let boxes = doc.symbol_boxes().quick(); + let source = boxes.symbol_art(symbol)?; + let size = match boxes.slice_map(symbol, *xf) { + Some(m) => m.most_placed_with(source, &boxes), + None => walk_size(source), + }; + if !ArtWalk::take(size) { + return None; + } + Self::drawn(doc, inst, false) + } + /// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the /// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell /// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides @@ -1751,15 +1871,18 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice /// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not /// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a -/// 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`. +/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. Elsewhere each +/// object is tested where the geometry effects of the instance's active fill and stroke draw it +/// ([`InstanceArt::drawn`]), and not where its own shape no longer paints. Live objects in the art +/// (blends, envelopes, repeats) are tested without those effects. `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 outline = opt.outline || below_preview_off(doc, inst, opt.scope); + let art = InstanceArt::drawn(doc, inst, outline)?; let symbols = doc.kept_symbol_boxes(); let mut path = vec![]; - let outline = opt.outline || below_preview_off(doc, inst, opt.scope); - let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false }; + let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true }; find.find(&art.art, &mut path, None, outline).map(|_| path) } @@ -1772,14 +1895,35 @@ struct FindPart<'a> { /// For [`instance_art_hit`]: locked and template objects of the art count, as the canvas draws /// them, and clipping paths are not picked by their outline. whole_instance: bool, + /// For [`symbol_part_at`] and [`drawn_instance_hit`]: the art carries the effects of the + /// instance's active fill and stroke ([`InstanceArt::drawn`]). + drawn: bool, } impl FindPart<'_> { /// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each - /// object it visits inside `n` from the [`ArtWalk`] limit. + /// object it visits inside `n` from the [`ArtWalk`] limit. In drawn art, a symbol instance with + /// geometry effects of its own, and type whose own effects or fill and stroke effects (its own, + /// or those the outer instance adds) reshape it, are hit only where the art they draw is + /// ([`own_effects_art`]), and an instance whose fill or stroke has geometry effects that reshape + /// its art (its own, or those the outer instance passes on) only where its art is drawn with + /// them ([`drawn_instance_hit`]); not anywhere in their bounds. With Type Object Selection by + /// Path Only ([`HitOptions::type_path_only`]), type is still picked by its type path. fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> Option { let placed = self.art.place(n, whole)?; let _charged = ArtWalk::charge(); + // Type Object Selection by Path Only picks type by its type path, whatever its effects draw. + let type_path = opt.type_path_only && matches!(placed.kind, NodeKind::Text(_)); + if self.drawn && !type_path { + if let Some(art) = own_effects_art(&placed, self.symbols, opt.outline) { + let _off = DrawnOff::set(); + let _art_only = ArtOnly::set(); + return hit_any(&art, self.p, opt, self.symbols); + } + if reshapes_instance_art(&placed, opt.outline) { + return drawn_instance_hit(&placed, self.p, opt, self.symbols); + } + } hit_any(&placed, self.p, opt, self.symbols) } @@ -1793,7 +1937,7 @@ impl FindPart<'_> { if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() { return None; } - let outline = outline || previews_off(n); + let outline = outline || !self.opt.ignore_layer_preview && previews_off(n); let opt = HitOptions { outline, ..self.opt }; let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) }; if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { @@ -1858,7 +2002,26 @@ fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) 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) + FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: false }.find(&art.art, &mut vec![], None, false) +} + +/// What a click at `p` hits of symbol instance `n`, an object of another instance's drawn art, +/// where the canvas draws `n`'s art with the geometry effects of `n`'s active fill and stroke +/// ([`InstanceArt::drawn`]): each object of that art where it is drawn, paths, images and type +/// alike, and not anywhere in `n`'s box. Locked and template objects of the art count, as in +/// [`instance_art_hit`]. `None` for an instance of a missing symbol, of a symbol that holds an +/// instance of itself or nests too deep ([`SymbolBoxes::art`]), of art past the 9-slice object +/// limit ([`InstanceArt::of`]), and once the click has visited as many objects of symbol art as +/// [`ArtWalk`] allows. +fn drawn_instance_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None }; + if symbols.art(symbol).is_none() || ArtWalk::used_up() { + return None; + } + let art = InstanceArt::nested(symbols.document(), n)?; + let opt = HitOptions { clip_outlines: false, ..opt }; + let _art_only = ArtOnly::set(); + FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: true }.find(&art.art, &mut vec![], None, false) } thread_local! { @@ -2008,15 +2171,21 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< /// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the /// outlines are cut to the bounds of the plain clipping paths, without their live effects, as /// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around -/// the object leave no region. +/// the object leave no region. Elsewhere the outlines follow the geometry effects of the instance's +/// active fill and stroke, as [`symbol_part_at`] does. Outlining visits at most as many objects of +/// symbol art as one click does ([`ArtWalk`]), the art of the instances nested in the part included, +/// and leaves out what is past that limit. pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { - let art = InstanceArt::of(doc, inst)?; - let part = crate::symbol_overrides::part(&art.art, path)?; + let _walk = ArtWalk::open(); let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); + let art = InstanceArt::drawn(doc, inst, outline)?; + let part = crate::symbol_overrides::part(&art.art, path)?; + let symbols = doc.kept_symbol_boxes(); let mut out = BezPath::new(); let mut limit = None; let mut whole = None; let mut n = &art.art; + let mut mask = false; for &i in path { let children = n.children()?; whole = art.whole(n, whole); @@ -2028,9 +2197,12 @@ pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], op let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) }; limit = within; } + mask = i == 0 && n.clips(); n = children.get(usize::try_from(i).ok()?)?; } - outline_within(&art.place(part, whole)?, limit, outline, &mut out); + // A clipping path is picked by its own geometry ([`FindPart::find`]), and outlined so. + let placed = art.place(part, whole)?; + plain(mask, || outline_within(&placed, &symbols, limit, outline, &mut out)); Some(out) } @@ -2052,9 +2224,42 @@ fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option, outline: bool, out: &mut BezPath) { +/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. A path +/// or compound path whose geometry effects reshape it is outlined as the art they draw +/// ([`drawn_art`]), a symbol instance with geometry effects of its own and type whose effects +/// reshape it as the art they draw ([`own_effects_art`]), and a symbol instance whose fill or +/// stroke effects reshape its art as that art drawn with them ([`InstanceArt::drawn`]), as +/// [`FindPart`] tests them, except with `outline` and while a [`DrawnOff`] guard lives. Each object +/// visited takes one object of the [`ArtWalk`] limit, and nothing more is outlined once the limit +/// is used up. A hidden object and what it holds are not outlined, as [`FindPart`] passes over them. +fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; + if !n.visible || !ArtWalk::take(1) { + return; + } + if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && let Some(art) = drawn_art(symbols, n, outline) + { + let _off = DrawnOff::set(); + art.iter().for_each(|a| outline_within(a, symbols, limit, outline, out)); + return; + } + if let Some(art) = own_effects_art(n, symbols, outline) { + let _off = DrawnOff::set(); + outline_within(&art, symbols, limit, outline, out); + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && reshapes_instance_art(n, outline) + { + if symbols.art(symbol).is_some() + && let Some(art) = InstanceArt::nested(symbols.document(), n) + && let Some(placed) = art.place(&art.art, None) + { + outline_within(&placed, symbols, limit, outline, out); + } + return; + } if let Some(pd) = n.path_data() { match limit { Some(r) => push_cut(out, &pd.to_bezpath(), r), @@ -2066,16 +2271,26 @@ fn outline_within(n: &Node, limit: Option, outline: bool, out: &mut BezPat { out.extend(b.to_path(0.1)); } + // An image is also outlined where its own fills and strokes paint with their effects, as + // [`hit_leaf`] picks it there ([`image_paint`]). + if !outline && matches!(n.kind, NodeKind::Image(_)) { + for (bp, ..) in image_paint(Some(symbols.document()), n).iter() { + match limit { + Some(r) => push_cut(out, bp, r), + None => out.extend(bp.iter()), + } + } + } let Some(children) = n.children() else { return }; let outline = outline || previews_off(n); if n.clips() && let Some((first, rest)) = children.split_first() { let Some(inner) = limit_within(first, limit, outline) else { return }; - rest.iter().for_each(|c| outline_within(c, inner, outline, out)); + rest.iter().for_each(|c| outline_within(c, symbols, inner, outline, out)); return; } - children.iter().for_each(|c| outline_within(c, limit, outline, out)); + children.iter().for_each(|c| outline_within(c, symbols, limit, outline, out)); } /// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap. diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index ad037931a0..a16b3ad149 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1324,11 +1324,11 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { assert_eq!(evaluated(), before + 2); } -/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to -/// (320, 20); nothing for anything else. +/// For instances of the symbols whose names start with "Painted", a fill that paints the square +/// from (300, 0) to (320, 20); nothing for anything else. fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { match &n.kind { - NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => { + NodeKind::SymbolInstance { symbol, .. } if symbol.starts_with("Painted") => { let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath(); vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))] } @@ -2831,6 +2831,32 @@ 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"); } +/// A symbol's art on a layer of the symbol whose Preview is off is hit in outline, unless the +/// click sets [`HitOptions::ignore_layer_preview`]: then the stroke past the instance's box hits. +#[test] +fn ignore_layer_preview_reaches_symbol_art_on_a_preview_off_layer() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + // A 20 pt stroke reaches 10 pt past the 0..100 square. + let look = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 20.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look); + let mut layer = Node::layer(d.alloc_id(), "Art", crate::LayerColor::Preset(2)); + if let NodeKind::Layer { children, preview, .. } = &mut layer.kind { + *children = vec![Arc::new(square)]; + *preview = false; + } + let art = Node::group(d.alloc_id(), vec![Arc::new(layer)]); + d.symbols.push(crate::Symbol { dynamic: false, name: "Stroked".into(), art: Arc::new(art) }); + let inst = d.alloc_id(); + let xf = vectorcraft_geom::Affine::IDENTITY; + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Stroked".into(), xf })).unwrap(); + let at = |x: f64, opt: HitOptions| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf); + let painted = HitOptions { ignore_layer_preview: true, ..HitOptions::default() }; + assert_eq!(at(108.0, HitOptions::default()), None, "Preview off: in outline"); + assert_eq!(at(108.0, painted), Some(inst), "ignore_layer_preview: on the stroke past the box"); + assert_eq!(at(116.0, painted), None, "past the stroke"); +} + /// 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 @@ -3041,6 +3067,119 @@ fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_li assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths"); } +/// Whether a symbol instance's fill or stroke effects reshape its art, for these tests: when +/// [`painted_far_away`] gives it shapes. +fn reshapes_when_painted(n: &Node) -> bool { + !painted_far_away(None, n).is_empty() +} + +/// An instance of the symbol named `symbol`, not moved, whose fill has a geometry effect: +/// [`reshapes_when_painted`] holds for it when the name starts with "Painted", so a part pick and a +/// part outline walk its art as drawn with its fill's effects ([`InstanceArt::drawn`]). +fn painted_instance_of(d: &mut Document, symbol: &str) -> Arc { + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); + n.appearance = Appearance::default_art().into(); + let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true }; + n.appearance.items[0].effects_mut().push(offset); + Arc::new(n) +} + +/// Five levels of symbols: "Painted 0" is a 1 pt square, and each level above holds 8 instances +/// of the level below whose fills have a geometry effect. Returns the id of an instance of +/// "Painted 4" on the layer. +fn painted_chain(d: &mut Document) -> NodeId { + let l = d.layers[0].id; + let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted 0".into(), art: Arc::new(dot) }); + for level in 1..5 { + let members = (0..8).map(|_| painted_instance_of(d, &format!("Painted {}", level - 1))).collect(); + group_symbol(d, &format!("Painted {level}"), members); + } + let inst = instance_of(d, "Painted 4"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + id +} + +/// The outline of a part of a dynamic symbol's instance visits at most the art walk's limit of +/// objects, though the part is an instance whose art, drawn with its fill's effects, nests +/// instances 3 levels deep, 8 at each level. Within the limit every square is outlined. +#[test] +fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() { + set_image_paint(painted_far_away); + set_instance_reshapes(reshapes_when_painted); + let mut d = Document::new(600.0, 400.0); + let id = painted_chain(&mut d); + let n = d.node(id).unwrap(); + let squares = |o: &BezPath| o.elements().iter().filter(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::MoveTo(_))).count(); + // Part [0] is an instance of "Painted 3": 8 × 8 × 8 squares. + assert_eq!(squares(&symbol_part_outline(&d, n, &[0]).unwrap()), 512, "within the limit"); + let (outline, _, arts) = with_art_limit(100, || symbol_part_outline(&d, n, &[0]).unwrap()); + assert!(squares(&outline) < 100, "{} squares outlined", squares(&outline)); + assert!(arts < 100, "{arts} instances' art walked"); +} + +/// A part pick in a dynamic symbol's instance visits at most the art walk's limit of objects of +/// nested instances whose art, drawn with their fills' effects, is walked: in a chain of nested +/// instances, and in instances whose clip groups the click misses, where only the clip group +/// itself is tested. A click on the clipped art of a nested instance is still found. +#[test] +fn a_part_pick_walks_nested_reshaped_symbol_instances_within_one_limit() { + set_image_paint(painted_far_away); + set_instance_reshapes(reshapes_when_painted); + let mut d = Document::new(600.0, 400.0); + let id = painted_chain(&mut d); + let opt = HitOptions::default(); + let (hit, _, arts) = with_art_limit(100, || symbol_part_at(&d, d.node(id).unwrap(), Point::new(150.0, 50.0), opt)); + assert_eq!(hit, None); + assert!(arts <= 40, "chain: {arts} instances' art walked"); + // 30 instances of a clip group whose 10 pt clipping path holds 40 squares: 42 objects each. + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()); + let mut members = vec![Arc::new(mask)]; + members.extend((0..40).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())))); + let mut clip = Node::group(d.alloc_id(), members); + clip.set_clips(true); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted clip".into(), art: Arc::new(clip) }); + let members = (0..30).map(|_| painted_instance_of(&mut d, "Painted clip")).collect(); + group_symbol(&mut d, "Clips", members); + let inst = instance_of(&mut d, "Clips"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + let n = d.node(id).unwrap(); + let (hit, _, arts) = with_art_limit(300, || symbol_part_at(&d, n, Point::new(150.0, 50.0), opt)); + assert_eq!(hit, None); + assert!(arts <= 8, "clip groups: {arts} instances' art walked"); + assert_eq!(with_art_limit(300, || symbol_part_at(&d, n, Point::new(2.0, 2.0), opt)).0, Some(vec![29]), "the clipped art"); +} + +/// The outline of a part of a dynamic symbol's instance leaves out the hidden objects in the art of +/// an instance nested in the part whose fill's effects reshape it, as a part pick passes over them. +#[test] +fn a_parts_outline_leaves_out_hidden_art_of_nested_reshaped_symbol_instances() { + use vectorcraft_geom::kurbo::Shape; + set_image_paint(painted_far_away); + set_instance_reshapes(reshapes_when_painted); + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let shown = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()); + let mut hidden = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(50.0, 50.0, 60.0, 60.0)), Appearance::default_art()); + hidden.visible = false; + group_symbol(&mut d, "Painted hidden", vec![Arc::new(shown), Arc::new(hidden)]); + let member = painted_instance_of(&mut d, "Painted hidden"); + group_symbol(&mut d, "Hides", vec![member]); + let inst = instance_of(&mut d, "Hides"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + let n = d.node(id).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(55.0, 55.0), HitOptions::default()), None, "the hidden square is not picked"); + let outline = symbol_part_outline(&d, n, &[0]).unwrap(); + let squares = outline.elements().iter().filter(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::MoveTo(_))).count(); + assert_eq!(squares, 1, "only the shown square is outlined"); + assert!(outline.bounding_box().x1 <= 1.0, "the outline reaches {:?}", outline.bounding_box()); +} + /// 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/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs index e6fe10022b..92f7f24758 100644 --- a/crates/doc/src/image_quad.rs +++ b/crates/doc/src/image_quad.rs @@ -479,6 +479,50 @@ mod tests { assert_eq!(read.image_quad(), Some(q)); } + /// An entry among the first four that is not a point, or a field that is not a list, drops the + /// corners and leaves the rest of the image read; the entries after a bad one are skipped. + #[test] + fn malformed_corners_a_file_holds_are_dropped_as_it_is_read() { + let n = image(100, 100); + let plain: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap(); + let bad_entries = [ + serde_json::json!([[40.0, 0.0], "not a point", [100.0, 100.0], [0.0, 100.0]]), + serde_json::json!([[40.0, 0.0], [60.0, 0.0], [100.0, 100.0], {"x": 1}]), + serde_json::json!([null, [60.0, 0.0], [100.0, 100.0], [0.0, 100.0]]), + serde_json::json!([[40.0, 0.0], [60.0], [100.0, 100.0], [0.0, 100.0], [5.0, 5.0]]), + serde_json::json!([[40.0, 0.0], [[1.0, 2.0], 3.0]]), + serde_json::json!([[40.0, 0.0], [60.0, 0.0, 1.0], [100.0, 100.0], [0.0, 100.0]]), + serde_json::json!([[40.0, 0.0], {"x": 60.0, "y": "0"}, [100.0, 100.0], [0.0, 100.0]]), + ]; + let bad_fields = [serde_json::json!("corners"), serde_json::json!(4), serde_json::json!(true), serde_json::json!({"a": [1.0, 2.0]})]; + for quad in bad_entries.into_iter().chain(bad_fields) { + let mut v = serde_json::to_value(&n).unwrap(); + v["image_quad"] = quad.clone(); + // File text, so the fields after the corners are read from the same stream. + let text = serde_json::to_string(&v).unwrap(); + let read: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{quad}: {e}")); + assert!(read.extras().image_quad.is_none(), "{quad}"); + assert!(!read.is_distorted_image(), "{quad}"); + assert_eq!(read, plain, "{quad}"); + assert_eq!(read.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 100.0)), "{quad}"); + } + // A point with a repeated coordinate. + let mut v = serde_json::to_value(&n).unwrap(); + v["image_quad"] = serde_json::json!([[40.0, 0.0], "SECOND", [100.0, 100.0], [0.0, 100.0]]); + let text = serde_json::to_string(&v).unwrap().replace("\"SECOND\"", r#"{"x":60.0,"y":0.0,"y":1.0}"#); + let read: Node = serde_json::from_str(&text).unwrap(); + assert_eq!(read, plain); + // Both forms of a point, whole numbers and unknown fields read as corners, from text and + // from a value. + let mut v = serde_json::to_value(&n).unwrap(); + v["image_quad"] = serde_json::json!([[40, 0], {"y": 0.0, "x": 60.0, "z": [1, 2]}, [100.0, 100.0], {"x": 0, "y": 100}]); + let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let read: Node = serde_json::from_str(&serde_json::to_string(&v).unwrap()).unwrap(); + assert_eq!(read.image_quad(), Some(q)); + let read: Node = serde_json::from_value(v).unwrap(); + assert_eq!(read.image_quad(), Some(q)); + } + #[test] fn refused_corners_change_nothing_and_a_bad_quad_in_a_file_is_ignored() { let mut n = image(10, 10); diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 9027c80b09..60a3c75d79 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -264,39 +264,188 @@ pub(super) struct NodeWire { } /// A distorted image's corners as a file holds them: a list of exactly four points, else none (the -/// image is then placed by its transform). At most five points of a longer list are kept while it -/// is read. +/// image is then placed by its transform). A point is `[x, y]` or `{"x": x, "y": y}`. A value that +/// is not a list, or a list with an entry that is not a point, is none too. Values that are not +/// taken are skipped as they are read, without being kept in memory, and at most four entries of a +/// longer list are decoded. fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result>, D::Error> { + use serde::de::{Deserializer, Error, IgnoredAny, MapAccess, SeqAccess, Visitor}; + use std::fmt::{Formatter, Result as FmtResult}; use vectorcraft_geom::Point; + + /// Skips the rest of a list; true when it held another entry. + fn rest_of_list<'de, A: SeqAccess<'de>>(mut seq: A) -> Result { + let mut more = false; + while seq.next_element::()?.is_some() { + more = true; + } + Ok(more) + } + fn rest_of_map<'de, A: MapAccess<'de>>(mut map: A) -> Result<(), A::Error> { + while map.next_entry::()?.is_some() {} + Ok(()) + } + // The visitors below give none for a value of a kind they do not take. + macro_rules! none_for { + (scalars) => { + fn visit_bool(self, _: bool) -> Result { + Ok(None) + } + fn visit_str(self, _: &str) -> Result { + Ok(None) + } + fn visit_unit(self) -> Result { + Ok(None) + } + fn visit_none(self) -> Result { + Ok(None) + } + }; + (numbers) => { + fn visit_i64(self, _: i64) -> Result { + Ok(None) + } + fn visit_u64(self, _: u64) -> Result { + Ok(None) + } + fn visit_f64(self, _: f64) -> Result { + Ok(None) + } + }; + (maps $de:lifetime) => { + fn visit_map>(self, map: A) -> Result { + rest_of_map(map)?; + Ok(None) + } + }; + } + + /// A coordinate: a number, else none. + struct Coord(Option); + impl<'de> serde::Deserialize<'de> for Coord { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> Visitor<'de> for V { + type Value = Option; + fn expecting(&self, f: &mut Formatter) -> FmtResult { + f.write_str("a number") + } + fn visit_i64(self, v: i64) -> Result { + Ok(Some(v as f64)) + } + fn visit_u64(self, v: u64) -> Result { + Ok(Some(v as f64)) + } + fn visit_f64(self, v: f64) -> Result { + Ok(Some(v)) + } + fn visit_seq>(self, seq: A) -> Result { + rest_of_list(seq)?; + Ok(None) + } + none_for!(scalars); + none_for!(maps 'de); + } + d.deserialize_any(V).map(Coord) + } + } + + /// The name of a point's field. + enum Key { + X, + Y, + Other, + } + impl<'de> serde::Deserialize<'de> for Key { + fn deserialize>(d: D) -> Result { + struct V; + impl Visitor<'_> for V { + type Value = Key; + fn expecting(&self, f: &mut Formatter) -> FmtResult { + f.write_str("a field name") + } + fn visit_str(self, v: &str) -> Result { + Ok(match v { + "x" => Key::X, + "y" => Key::Y, + _ => Key::Other, + }) + } + } + d.deserialize_identifier(V) + } + } + + /// One entry of the list: a point, else none. + struct Corner(Option); + impl<'de> serde::Deserialize<'de> for Corner { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> Visitor<'de> for V { + type Value = Option; + fn expecting(&self, f: &mut Formatter) -> FmtResult { + f.write_str("a point") + } + fn visit_seq>(self, mut seq: A) -> Result { + let x = seq.next_element::()?.and_then(|c| c.0); + let y = match x { + Some(_) => seq.next_element::()?.and_then(|c| c.0), + None => None, + }; + let more = rest_of_list(seq)?; + Ok(x.zip(y).filter(|_| !more).map(|(x, y)| Point::new(x, y))) + } + fn visit_map>(self, mut map: A) -> Result { + let (mut x, mut y, mut bad) = (None, None, false); + while let Some(key) = map.next_key::()? { + let slot = match key { + Key::X => &mut x, + Key::Y => &mut y, + Key::Other => { + map.next_value::()?; + continue; + } + }; + let v = map.next_value::()?.0; + // A repeated or non-numeric coordinate makes the entry no point. + bad |= slot.is_some() || v.is_none(); + *slot = slot.or(v); + } + Ok(x.zip(y).filter(|_| !bad).map(|(x, y)| Point::new(x, y))) + } + none_for!(scalars); + none_for!(numbers); + } + d.deserialize_any(V).map(Corner) + } + } + struct Corners; - impl<'de> serde::de::Visitor<'de> for Corners { + impl<'de> Visitor<'de> for Corners { type Value = Option>; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, f: &mut Formatter) -> FmtResult { f.write_str("a list of points") } - fn visit_none(self) -> Result { - Ok(None) + fn visit_some>(self, d: D) -> Result { + d.deserialize_any(Corners) } - fn visit_unit(self) -> Result { - Ok(None) - } - fn visit_some>(self, d: D) -> Result { - d.deserialize_seq(Corners) - } - fn visit_seq>(self, mut seq: A) -> Result { + fn visit_seq>(self, mut seq: A) -> Result { let mut points = Vec::with_capacity(4); - while points.len() < 4 - && let Some(p) = seq.next_element::()? - { - points.push(p); + let mut malformed = false; + while points.len() < 4 && !malformed { + match seq.next_element::()? { + Some(Corner(Some(p))) => points.push(p), + Some(Corner(None)) => malformed = true, + None => break, + } } - // A fifth entry drops the field, so the rest is skipped without decoding it. - let mut extra = false; - while seq.next_element::()?.is_some() { - extra = true; - } - Ok(if extra { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) }) + // A malformed or fifth entry drops the field, so the rest is skipped without decoding it. + let extra = rest_of_list(seq)?; + Ok(if extra || malformed { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) }) } + none_for!(scalars); + none_for!(numbers); + none_for!(maps 'de); } d.deserialize_option(Corners) } diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 9c5c278a53..d7c24934e0 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -1,6 +1,6 @@ //! The batched lookups ([`Document::index_paths`], `node_at`, `node_mut_at`, `ancestry_at`) agree //! with the one-id ones on nested trees with missing and duplicated ids, and the edits of many nodes -//! ([`Document::remove_many`], `wrap`, `insert_beside`) leave the tree that `remove`, `insert` and +//! ([`Document::remove_many`], `wrap`, `insert_beside`, `insert_below`) leave the tree that `remove`, `insert` and //! `move_node` leave one node at a time. use crate::*; use vectorcraft_geom::shapes; @@ -290,6 +290,26 @@ fn insert_beside_matches_inserting_one_at_a_time() { } } +#[test] +fn insert_below_matches_inserting_one_at_a_time() { + for seed in 1..40 { + let (mut d, mut ids) = tree(seed); + let picked = picks(&d, seed); + // None to three new nodes for each anchor. + let items: Vec<(NodeId, Vec)> = picked.iter().enumerate().map(|(k, id)| (*id, (0..k % 4).map(|_| square(&mut d)).collect())).collect(); + ids.extend(items.iter().flat_map(|(_, new)| new.iter().map(|n| n.id))); + let (mut a, mut b) = (d.clone(), d.clone()); + for (id, new) in items.clone() { + let (parent, at, _) = a.position(id).unwrap(); + for (k, n) in new.into_iter().enumerate() { + a.insert(parent, at + k, n).unwrap(); + } + } + b.insert_below(items).unwrap(); + same(&a, &b, &ids, &format!("seed {seed}")); + } +} + #[test] fn wrap_matches_inserting_a_group_and_moving_the_nodes_into_it_one_at_a_time() { for seed in 1..40 { @@ -331,6 +351,8 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() { let items = list.iter().map(|id| (*id, vec![])).collect(); assert_eq!(b.insert_beside(items, replace).err(), Some(DocError::NoNode(bad)), "{what}"); } + let items = list.iter().map(|id| (*id, vec![])).collect(); + assert_eq!(b.insert_below(items).err(), Some(DocError::NoNode(bad)), "{what}"); assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was"); } } diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c46ab0c76e..46fd9344e2 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -89,9 +89,9 @@ pub use raster::{ without_geometry, }; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies, - has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, - instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, + SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, + has_gradient_copies, has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, + has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index a57c2085f6..c7ab85e7a8 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -388,11 +388,23 @@ fn row_effects_of(fx: &[Effect]) -> Vec { /// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no /// instance in the art takes them. pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { + add_instance_rows(doc, n, art, true); +} + +/// [`add_instance_row_effects`] for Direct Selection's parts of a symbol instance's art: live +/// objects (blends, envelopes, repeats) are left as they are, without the effects, so that every +/// object keeps its place in the art and the child indices that pick a part still lead to it. +pub fn add_instance_row_effects_to_parts(doc: Option<&Document>, n: &Node, art: &mut Node) { + add_instance_rows(doc, n, art, false); +} + +/// [`add_instance_row_effects`], evaluating live objects in the art only with `live`. +fn add_instance_rows(doc: Option<&Document>, n: &Node, art: &mut Node, live: bool) { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects)); let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects)); if !fill.is_empty() || !stroke.is_empty() { - add_row_effects(doc, symbol, art, &fill, &stroke); + add_row_effects(doc, symbol, art, &fill, &stroke, live); } } @@ -413,8 +425,9 @@ fn places_symbol(doc: &Document, from: &str, to: &str, seen: &mut HashSet, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect]) { +/// instance of the symbol named `outer`. Without `live`, live objects are left as they are +/// ([`add_instance_row_effects_to_parts`]). +fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect], live: bool) { match &n.kind { NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => return, NodeKind::SymbolInstance { symbol, .. } => { @@ -425,7 +438,12 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef } return; } - _ if vectorcraft_doc::live::is_live(n) => *n = evaluated(doc, n), + _ if vectorcraft_doc::live::is_live(n) => { + if !live { + return; + } + *n = evaluated(doc, n); + } _ => {} } let takes = |i: &AppearanceItem| { @@ -445,7 +463,7 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef let clips = n.clips(); for (i, c) in n.children_mut().into_iter().flatten().enumerate() { if !(clips && i == 0) { - add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke); + add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke, live); } } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 075211dc1a..cf21c25e46 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -19,6 +19,7 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"] heif = ["dep:heic-rs", "dep:rayon"] [dependencies] +craft-codepage = { workspace = true } # Which paths stored in documents may be opened. craft-docpath = { workspace = true } craft-proof = { workspace = true } diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 037983da5c..99ccd2d828 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -398,15 +398,6 @@ pub(crate) fn aligned(p: &Value, cmd: &str) -> Result { switch_or(p, "aligned", false, cmd) } -/// What the appearances of `ids` share, when there are several of them and they all exist. -pub(crate) fn shared_stack(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Option { - if ids.len() < 2 { - return None; - } - let aps: Vec<&Appearance> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect::>()?; - Some(SharedStack::of(&aps)) -} - /// Do the appearances of `ids` differ (several objects whose stacks aren't all equal)? pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> bool { let mut aps = ids.iter().filter_map(|id| d.node(*id)).map(|n| &n.appearance); @@ -1530,19 +1521,16 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { let mut first_at = None; let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); let mut active_at = None; - // Aligned rows of a mixed selection are copied right above themselves in each object. Rows of a graph design's art, - // which is left out, go to `to` in an object whose stack is the same as the art's. + // Aligned rows of a mixed selection are copied right above themselves in each object. Aligned rows of objects whose + // stacks are the same, and rows of a graph design's art, which is left out, go to `to` as in one stack. let of = design_reference(s, p, C)?; - if aligned(p, C)? - && to.is_some() - && (shared_stack(&s.doc()?.doc, &ids).is_some() || (of.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids)))) - { + if aligned(p, C)? && to.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids)) { return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows")); } let before = s.doc()?.doc.clone(); - // With `to`, the art's stack is the same as the object's, so its rows are the object's, each of which must exist. - let per = - if to.is_some() { items_per_target(&before, &ids, &idx, aligned(p, C)?) } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) }; + // With `to`, aligned rows are rows of stacks that are all the same (the art's too), so each target takes the same + // indices, each of which must exist. + let per = if to.is_some() { vec![idx.clone(); ids.len()] } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) }; s.edit("Duplicate Item", |d, _| { let mut any = false; // Copies that became the topmost visible row of their kind: the series stores their paint even when the object diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..e248f2bbc3 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Flare", [], None, - "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}", + "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end, both or neither: one alone is an error; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}", has_doc, super::flare::flare ), diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index e38f8f99bb..9f631aafd2 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Update Dimensions", [], None, - "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}", + "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}", has_doc, update ), @@ -159,6 +159,7 @@ fn update(s: &mut Session, p: &Value) -> Result { return Err(error("Select dimensions to update")); } let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None }; + let at = if p.get("at").is_some() { Some(point(p, "at")?) } else { None }; // Every dimension is checked before anything changes, and an update that changes none of // them records no undo step. let mut next = Vec::with_capacity(ids.len()); @@ -178,6 +179,10 @@ fn update(s: &mut Session, p: &Value) -> Result { } dim.offset = distance(p, dim.offset)?; dim.resolve(doc).map_err(error)?; + if let Some(at) = at { + dim.place(at); + dim.resolve(doc).map_err(error)?; + } if dim != old { next.push((*id, dim)); } diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 90d58541a6..6589fd3468 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -231,7 +231,7 @@ fn persp_edit( let d = &s.doc()?.doc; fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none())) }; - let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None }; + let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false, false)? } else { None }; let edited = s.edit(label, |d, sel| { g.adopt_stored_attachments(d); let targets = match &kept { @@ -502,7 +502,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { // lists attachments of its own (`stores_attachments`). let kept = if objects == "copy" && s.in_interaction() && !stores_attachments(&s.doc()?.doc) { let on = on_plane(&s.doc()?.doc); - crate::cmd::object::preview_copies(s, &on, false)? + crate::cmd::object::preview_copies(s, &on, false, false)? } else { None }; diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e4846367b5..9c3dcbd47a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes", has_selection, smooth_region ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Join", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12; from 0.001 to 1000)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}. A tolerance outside 0.001 to 1000 is refused with an error, and nothing changes", has_doc, join_scrub ), diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..b5291b4621 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,9 +1,10 @@ use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_pathops::start_nearest; -use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; +use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, ranged, subpath_len, target_paths}; use super::{ - Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json, - number_or, po, + Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, bad, + json, number_or, po, }; // ---------- Smooth ---------- @@ -323,84 +324,6 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec (usize, f64) { - let mut best: Option<(f64, usize, f64)> = None; - for j in 0..orig.anchors.len() { - let hit = orig.segment(j).nearest(p, 1e-9); - if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { - best = Some((hit.distance_sq, j, hit.t)); - } - } - best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) -} - -/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new -/// anchor split into the segment there, which leaves the outline as it is. Of points equally near -/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used, -/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point, -/// is returned as it is. -fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath { - let n = sp.anchors.len(); - if !sp.closed || n < 2 { - return sp; - } - // (distance, place along `orig` once a tie needs it, segment of `sp`, parameter) - type Best = (f64, Option<(usize, f64)>, usize, f64); - let mut best: Option = None; - for i in 0..n { - let c = sp.segment(i); - let hit = c.nearest(start, 1e-9); - if !hit.distance_sq.is_finite() || !hit.t.is_finite() { - continue; - } - let d = hit.distance_sq.sqrt(); - match &mut best { - None => best = Some((d, None, i, hit.t)), - Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => { - let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt))); - let place = place_along(orig, c.eval(hit.t)); - if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { - best = Some((d, Some(place), i, hit.t)); - } - } - Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)), - Some(_) => {} - } - } - let Some((_, _, i, t)) = best else { return sp }; - let c = sp.segment(i); - let at = c.eval(t); - let first = if at.distance(c.p0) <= START_SNAP { - i - } else if at.distance(c.p3) <= START_SNAP { - (i + 1) % n - } else { - let mid = if sp.segment_is_line(i) { - Anchor::corner(at) - } else { - let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); - sp.anchors[i].h_out = l.p1; - sp.anchors[(i + 1) % n].h_in = r.p2; - Anchor::with_handles(at, l.p2, r.p1) - }; - sp.anchors.insert(i + 1, mid); - i + 1 - }; - sp.anchors.rotate_left(first); - sp -} - /// Pieces of curve that one Smooth drag measures against the drag while it searches the segments /// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach, /// each of which gets at least one: enough to search 300,000 pt of curve within the default reach @@ -645,14 +568,28 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f (!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false)) } -/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it -/// enters the reach: the part outside, then the part in reach. `None` when no more than a sliver -/// is outside. -fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez, CubicBez)> { +/// How much of a segment that ends in the drag's reach is in reach ([`split_at_reach`]). +enum Reach { + /// All of it, or all but a sliver. + Whole, + /// No more than a sliver at its end. + End, + /// The part outside the reach, then the part in reach. + Split(CubicBez, CubicBez), +} + +/// Share of the tool's reach that the part of a segment in reach must be longer than for +/// [`split_at_reach`] to split the segment. VectorCraft's own value. +const REACH_SLIVER: f64 = 1.0 / 64.0; + +/// The segment `c`, which ends in the drag's reach (`near`, `radius` points) and starts outside it, +/// split where it enters the reach. No more than 2% of its parameter range outside the reach is a +/// sliver, and so is a part in reach no longer than [`REACH_SLIVER`] of the reach. +fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool, radius: f64) -> Reach { const STEPS: u32 = 32; let step = 1.0 / f64::from(STEPS); // Back from the end in reach to the first sample outside, then halving to the crossing. - let outside = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t)))?; + let Some(outside) = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t))) else { return Reach::Whole }; let (mut lo, mut hi) = (outside, outside + step); for _ in 0..20 { let mid = (lo + hi) / 2.0; @@ -668,7 +605,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez let s = c.subsegment(range); if straight { CubicBez::new(s.p0, s.p0, s.p3, s.p3) } else { s } }; - (hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0))) + if hi <= 0.02 { + return Reach::Whole; + } + let (far, reach) = (part(0.0..hi), part(hi..1.0)); + if polygon_len(reach) <= REACH_SLIVER * radius { Reach::End } else { Reach::Split(far, reach) } } /// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted @@ -695,25 +636,33 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool } let mut out = anchors.to_vec(); for (a, b) in runs.into_iter().rev() { - let lo = a.saturating_sub(1); - let hi = (b + 1).min(n - 1); + let (mut lo, mut hi) = (a.saturating_sub(1), (b + 1).min(n - 1)); + // How much of the segments leading out of the run is in reach. A segment that is in reach + // only at the run's anchor stays out of the piece, so the piece ends at that anchor rather + // than in a sliver of a segment, which would leave the refit no direction to end along. + let after = if hi > b { split_at_reach(CubicBez::new(out[hi].p, out[hi].h_in, out[b].h_out, out[b].p), near, radius) } else { Reach::Whole }; + let before = if lo < a { split_at_reach(CubicBez::new(out[lo].p, out[lo].h_out, out[a].h_in, out[a].p), near, radius) } else { Reach::Whole }; + if matches!(after, Reach::End) { + hi = b; + } + if matches!(before, Reach::End) { + lo = a; + } if hi == lo { continue; } let mut piece = out[lo..=hi].to_vec(); // The anchors outside the reach, kept with the part of their segment that is outside. let (mut head, mut tail) = (None, None); - if hi > b + if let Reach::Split(far, reach) = after && let [.., inner, outer] = piece.as_mut_slice() - && let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_in, inner.h_out, inner.p), near) { inner.h_out = reach.p2; tail = Some(Anchor { h_in: far.p1, ..*outer }); *outer = Anchor::with_handles(far.p3, reach.p1, far.p2); } - if lo < a + if let Reach::Split(far, reach) = before && let [outer, inner, ..] = piece.as_mut_slice() - && let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_out, inner.h_in, inner.p), near) { inner.h_in = reach.p2; head = Some(Anchor { h_out: far.p1, ..*outer }); @@ -733,8 +682,12 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.smoothRegion"; let pts = points_param(p, "points", C)?; - let radius = number_or(p, "radius", 12.0, C)?.max(0.0); - let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + let radius = ranged(p, "radius", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?; + let tol = number_or(p, "fidelity", 2.5, C)?; + let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + if !(lo..=hi).contains(&tol) { + return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt"))); + } let sigma = radius * SMOOTH_SPREAD; let st = s.doc()?; let mut plan = vec![]; @@ -882,7 +835,7 @@ fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol: pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { const C: &str = "path.joinScrub"; let pts = points_param(p, "points", C)?; - let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0); + let tol = ranged(p, "tolerance", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?; let st = s.doc()?; let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)); // Paths that cross with their ends scrubbed are trimmed there and joined (#5844). @@ -1009,6 +962,8 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { + use vectorcraft_pathops::START_SNAP; + use super::*; /// A closed ring of four smooth anchors round (100, 100) with radius 50. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccebbfac88..a20a6c47e4 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1828,7 +1828,19 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { /// Duplicate `roots` directly above each original, transform the copies, select them /// ([`copy_above`]). pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selection, roots: &[NodeId], xf: Affine) -> Result> { - let out = copy_above(d, roots, |_, _, c| { + duplicate_beside(d, sel, roots, xf, false) +} + +/// [`duplicate_in`], with each copy directly below its original when `below` is true +/// ([`copy_beside`]). +pub(crate) fn duplicate_beside( + d: &mut Document, + sel: &mut vectorcraft_doc::Selection, + roots: &[NodeId], + xf: Affine, + below: bool, +) -> Result> { + let out = copy_beside(d, roots, below, |_, _, c| { c.transform(xf, true); super::object::keep_pixel_aligned(c, true.into()); })?; @@ -1841,20 +1853,42 @@ pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selectio /// tree as it is. The copies take new ids in the order of `roots`. Roots listed twice, or inside /// another root, are copied one at a time: each copy is made from the document as the copies /// before it left it. Copied type whose layout caches [`Document::reid`] dropped has them again. -pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result> { +pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result> { + copy_beside(d, roots, false, change) +} + +/// [`copy_above`], with each copy directly below its original, in the same parent, when `below` +/// is true. The clipping path of a clip group or a clipping layer stays the bottom child: its copy +/// goes directly above it. +pub(crate) fn copy_beside( + d: &mut Document, + roots: &[NodeId], + below: bool, + mut change: impl FnMut(&mut Document, &Node, &mut Node), +) -> Result> { let paths = d.index_paths(roots.iter().copied()); let mut found: Vec<_> = roots.iter().filter_map(|id| paths.get(id)).collect(); found.sort_unstable(); + // The bottom child of a parent that clips is its clipping path. + let clips_at = |d: &Document, up: &[usize], i: usize| i == 0 && !up.is_empty() && d.node_at(up).is_some_and(Node::clips); let out = if found.windows(2).all(|w| !w[1].starts_with(w[0])) { - let mut copies = Vec::with_capacity(roots.len()); + let (mut copies, mut above) = (Vec::with_capacity(roots.len()), vec![]); + let mut out = Vec::with_capacity(roots.len()); for id in roots { - let Some(n) = paths.get(id).and_then(|p| d.node_at(p)).cloned() else { continue }; + let Some(p) = paths.get(id) else { continue }; + let Some(n) = d.node_at(p).cloned() else { continue }; let mut c = d.reid(&n); change(d, &n, &mut c); - copies.push((*id, vec![c])); + out.push(c.id); + let on_floor = below && p.split_last().is_some_and(|(i, up)| clips_at(d, up, *i)); + if !below || on_floor { above.push((*id, vec![c])) } else { copies.push((*id, vec![c])) } + } + if !copies.is_empty() { + d.insert_below(copies)?; + } + if !above.is_empty() { + d.insert_beside(above, false)?; } - let out: Vec = copies.iter().flat_map(|(_, c)| c.iter().map(|n| n.id)).collect(); - d.insert_beside(copies, false)?; out } else { let mut out = vec![]; @@ -1863,7 +1897,8 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn let Some(n) = d.node(*id).cloned() else { continue }; let mut c = d.reid(&n); change(d, &n, &mut c); - out.push(d.insert(par, idx + 1, c)?); + let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips)); + out.push(d.insert(par, if below { idx.max(floor) } else { idx + 1 }, c)?); } out }; diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index cb399eca1c..f29e2e3745 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a visible plain instance outside template layers in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", can_expand, expand_appearance ), @@ -927,7 +927,8 @@ fn bevel_effect(id: &str) -> bool { /// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their /// defaults is unchanged), each option given equal to the one it stores (a precision that Scale /// Strokes & Effects took past its range evaluates at the bound but is still edited), and every -/// other value given equal to the one it has? +/// other value given equal to the one it has (a number by its value, so a Soft Mix `mixingRate` of 50 +/// over a stored 50.0 is unchanged)? fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool { if !effects::takes_pathfinder_options(&e.id) { return false; @@ -938,8 +939,12 @@ fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool { if let Value::Object(m) = &mut after { m.extend(given.clone()); } - let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v)); - let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x)); + // Two integers compare exactly, and a float compares with any number by value. + let same_value = |a: &Value, b: &Value| a == b || ((a.is_f64() || b.is_f64()) && a.as_f64().is_some_and(|x| b.as_f64() == Some(x))); + let others_same = given + .iter() + .filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())) + .all(|(k, v)| current.get(k).is_some_and(|c| same_value(c, v))); let stored_same = given .iter() .filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())) @@ -1611,33 +1616,72 @@ fn expanded_node( /// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that /// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an -/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does -/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's +/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does), or that the +/// image of a group or layer with a raster effect draws ([`rasterizes_plugin_effect`]). A symbol's /// art counts where an instance of it expands. `seen` holds the symbols already looked into. fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet) -> bool { - let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); let mut symbols = vec![]; - let mut drawn = vec![]; let mut holds = false; n.walk(&mut |c| { - if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() { - drawn.push(c); - } if !in_art && !expandable(c) { return; } - holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin)); + holds |= has_own_plugin_effect(c); if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { symbols.push(symbol.clone()); } }); holds - || drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen)) + || (!in_art && rasterizes_plugin_effect(d, n, &mut std::collections::HashSet::new())) || symbols.into_iter().any(|name| { seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen)) }) } +/// Does `n` have a visible plug-in effect of its own, or on a visible fill or stroke? +fn has_own_plugin_effect(n: &Node) -> bool { + let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); + n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin)) +} + +/// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect +/// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or +/// a group around it, is hidden. A group or layer that paints something and whose raster effects +/// are not all shadows and outer glows becomes one image of what it draws, so the groups and layers +/// in it make no images of their own; one that paints nothing makes no image, and its members +/// expand on their own. +fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { + let fx = if is_container(n) { rasterfx::raster_fx(n) } else { vec![] }; + if !fx.is_empty() { + if draws_plugin_effect(d, n, seen) { + return true; + } + if !fx.iter().all(effects::RasterFx::is_below) && vectorcraft_render::painted_bounds(d, n).is_some() { + return false; + } + } + n.children().into_iter().flatten().any(|c| rasterizes_plugin_effect(d, c, seen)) +} + +/// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places, +/// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object +/// in `n`, a template layer, a guide or a ruler guide, and everything in it, as the renderer does +/// with templates skipped. `seen` holds the symbols already looked into. +fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { + if has_own_plugin_effect(n) { + return true; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && seen.insert(symbol.clone()) + && d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| draws_plugin_effect(d, &s.art, seen)) + { + return true; + } + let drawn = + |c: &Node| c.visible && !c.is_ruler_guide() && !matches!(c.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. }); + n.children().into_iter().flatten().any(|c| drawn(c) && draws_plugin_effect(d, c, seen)) +} + fn expand_appearance(s: &mut Session, p: &Value) -> Result { let roots = edit_targets(s, p, "effect.expandAppearance")?; // In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 17e6c3f814..67958a550b 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -32,12 +32,35 @@ //! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its //! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need //! a merge (one in a mode VectorCraft lacks, one with a knockout in a group that changes the layers -//! below it, one that layers are clipped to, one clipped to another, or one below a merged layer) is -//! always left out, with the layers clipped to it. Adjustment layers, fill layers that store no -//! pixels and whose fill isn't read or whose shape is a vector mask, layer effects that are switched -//! on, vector masks, and the knockouts of top-level layers, of clipped layers, of layers that others -//! are clipped to and of layers in a pass-through group with a layer in another mode, and other -//! Knockout values, aren't applied; the warnings count them and the hidden layers left out. +//! below it, one that layers are clipped to, one clipped to another, an Invert, Threshold or +//! Posterize adjustment layer, or one below a merged layer) is always left out, with the layers +//! clipped to it. +//! +//! An Invert, Threshold or Posterize adjustment layer, as the import option describes for +//! adjustment layers, is merged with the visible layers below it in its group, which it changes; +//! clipped to a layer, it changes only the layers merged into that one. The rules are VectorCraft's +//! own: each color channel is taken as an 8-bit value of the sRGB color the layers are drawn in, +//! Invert turns `v` into `255 − v`, Threshold makes a pixel white when the luminance of its color +//! (Rec. 709 weights on linear sRGB, encoded back to 0..255) is above the level and black +//! otherwise, and Posterize maps each channel to the nearest of its evenly spaced levels, the higher +//! one on a tie. The adjusted color is composited over the color below in the layer's blend mode, +//! at its opacity times its fill opacity, through its layer mask; transparency stays as it was. One +//! with nothing visible below it in its group that draws (a layer that stores no pixels, other than +//! a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 +//! opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) +//! changes nothing; in a pass-through group it changes +//! what is below the group when the group is merged, and otherwise isn't applied. One that layers +//! are clipped to, and one clipped to another adjustment layer, isn't applied. One whose layer mask +//! needs more memory than allowed beside the canvases it would change isn't applied, and a clip, or +//! a merge for another layer, that it is part of goes on without it. +//! +//! Other adjustment layers, Invert, Threshold and Posterize data that can't be read (a level out of +//! range, too short, or a second adjustment block on the layer), fill layers that store no pixels and +//! whose fill isn't read or whose shape is a vector mask, layer effects that are switched on, vector +//! masks, and the knockouts of top-level layers, of clipped layers, of layers that others are clipped +//! to and of layers in a pass-through group with a layer in another mode, and other Knockout values, +//! and adjustments whose merge, their layer mask included, needs more memory than allowed aren't applied; the warnings count them +//! and the hidden layers left out. //! //! The file is untrusted: every count, length and size is checked before anything is allocated, //! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the @@ -193,8 +216,9 @@ enum Content { Pixels, /// A type layer: its pixels come in. Type, - /// An adjustment layer: not applied. - Adjustment, + /// An adjustment layer: the adjustment applied (`None` for another kind, or data that can't be + /// read, which isn't applied). + Adjustment(Option), /// A solid color fill layer: its stored pixels, or its color over the whole canvas when it /// stores none (nothing when the color can't be read, or when its shape is a vector mask). Solid(Option), @@ -202,6 +226,58 @@ enum Content { Fill, } +/// An adjustment the import applies. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Adjust { + /// `nvrt`: each color channel's value `v` (0..255) becomes `255 − v`. + Invert, + /// `thrs`: pixels whose luminance is above the level (1..255) become white, the others black. + Threshold(u8), + /// `post`: each color channel takes the nearest of this many (2..255) evenly spaced levels. + Posterize(u8), +} + +impl Adjust { + /// The adjustment of key `key` whose data is `data`; `None` when the data can't be read or its + /// value is out of range. Invert has no data; Threshold's level and Posterize's count of levels + /// are a 16-bit number followed by 2 bytes of padding, as psd-tools (MIT) reads them + /// (, `psd/adjustments.py`); data shorter than the 4 + /// bytes can't be read. + fn read(key: &[u8; 4], data: &[u8]) -> Option { + let value = || data.get(..4).map(|v| u16::from_be_bytes([v[0], v[1]])); + match key { + b"nvrt" => Some(Adjust::Invert), + b"thrs" => u8::try_from(value()?).ok().filter(|&l| l >= 1).map(Adjust::Threshold), + b"post" => u8::try_from(value()?).ok().filter(|&n| n >= 2).map(Adjust::Posterize), + _ => None, + } + } + + /// Straight RGB, 0..1, adjusted. Each channel is taken as an 8-bit value. Threshold measures + /// the sRGB relative luminance (Rec. 709 weights on the linear values), encoded back to 0..255: + /// above the level is white, at or below it black. Posterize maps a value to the nearest of + /// its levels `k × 255 / (n − 1)`, the higher one on a tie. + fn apply(self, rgb: [f32; 3]) -> [f32; 3] { + use vectorcraft_color::cms::lab::{linear_to_srgb, srgb_to_linear}; + let v = rgb.map(byte); + match self { + Adjust::Invert => v.map(|v| f32::from(255 - v) / 255.0), + Adjust::Threshold(level) => { + let lin = v.map(|v| srgb_to_linear(f32::from(v) / 255.0)); + let y = byte(linear_to_srgb(0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2])); + [if y > level { 1.0 } else { 0.0 }; 3] + } + Adjust::Posterize(n) => { + let steps = u32::from(n) - 1; + v.map(|v| { + let k = (2 * u32::from(v) * steps + 255) / 510; + ((2 * k * 255 + steps) / (2 * steps)) as f32 / 255.0 + }) + } + } + } +} + /// A solid color fill layer's color. #[derive(Clone, Copy, Debug, PartialEq)] enum Paint { @@ -333,6 +409,8 @@ impl Record<'_> { // Effects in a descriptor (`lfx2`, `lmfx`) say whether they are switched on; the older // `lrFX` block is counted whenever it is there. let (mut effects, mut old_effects) = (None, false); + // Whether an adjustment block has been read. + let mut adjusted = false; while e.rest().len() >= 12 { let (Ok(signature), Ok(key)) = (e.array::<4>(), e.array::<4>()) else { break }; if !matches!(&signature, b"8BIM" | b"8B64") { @@ -363,7 +441,12 @@ impl Record<'_> { b"lrFX" => old_effects = true, b"vmsk" | b"vsms" => self.vector_mask = true, b"knko" => self.knockout = data.first().copied().unwrap_or(0), - k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment, + // A second adjustment block, with other blocks between them or not, makes the + // layer's adjustment unreadable. + k if ADJUSTMENTS.contains(&k) => { + let again = std::mem::replace(&mut adjusted, true); + self.content = Content::Adjustment(Adjust::read(k, data).filter(|_| !again)); + } _ => {} } // Some writers pad blocks further: skip to the next signature. @@ -390,17 +473,31 @@ impl Record<'_> { matches!(self.content, Content::Solid(Some(_))) && self.stores_nothing() && !self.vector_mask } + /// The adjustment the layer applies, if it is an adjustment layer of a kind the import applies. + fn adjust(&self) -> Option { + match self.content { + Content::Adjustment(a) => a, + _ => None, + } + } + /// Does the layer cover the whole canvas without drawing (an adjustment layer, or a fill that /// stores no pixels, has no vector mask and isn't drawn from its color)? Layers clipped to it /// show over the whole canvas. fn covers_without_drawing(&self) -> bool { match self.content { - Content::Adjustment => true, + Content::Adjustment(_) => true, Content::Solid(None) | Content::Fill => self.stores_nothing() && !self.vector_mask, _ => false, } } + /// Does the layer draw nothing (an adjustment layer, or one that stores no pixels and isn't a + /// fill drawn from its color over the canvas; see [`Builder::image`])? + fn draws_nothing(&self) -> bool { + self.covers_without_drawing() || (self.stores_nothing() && !self.color_over_canvas()) + } + /// Is the layer a fill that stores no pixels and whose shape is a vector mask, so that it /// isn't drawn? fn undrawn_shape(&self) -> bool { @@ -488,6 +585,15 @@ enum Item { Group(usize, Vec), } +/// The layers of the group of record `g`, looked for in `items` and the groups inside them. +fn find_group(items: &[Item], g: usize) -> Option<&[Item]> { + items.iter().find_map(|item| match item { + Item::Group(i, children) if *i == g => Some(children.as_slice()), + Item::Group(_, children) => find_group(children, g), + Item::Layer(_) => None, + }) +} + fn tree(records: &[Record<'_>]) -> Result, String> { let mut stack: Vec> = vec![vec![]]; for (i, rec) in records.iter().enumerate() { @@ -701,6 +807,9 @@ enum Drawn { struct Notes { types: usize, adjustments: usize, + /// Adjustment layers of a kind the import applies that it couldn't apply (warned of with + /// `adjustments`). + unadjusted: usize, fills: usize, effects: usize, vector_masks: usize, @@ -730,6 +839,8 @@ struct Counts { clipped_out: usize, /// The groups found to read no pixels. blank: usize, + /// The adjustment layers counted as not applied (see [`Builder::unadjust`]). + unadjusted: usize, } /// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place @@ -778,7 +889,7 @@ impl Notes { let [types, adjustments, fills, effects, masks, knockouts, hidden, clipped_out, unmerged, unclipped] = LAYER_WARNINGS; let mut out = vec![]; note(&mut out, self.types, types); - note(&mut out, self.adjustments, adjustments); + note(&mut out, self.adjustments + self.unadjusted, adjustments); note(&mut out, self.fills, fills); note(&mut out, self.effects, effects); note(&mut out, self.vector_masks, masks); @@ -793,7 +904,7 @@ impl Notes { out } - fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize) -> Counts { + fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize, unadjusted: usize) -> Counts { Counts { spent, skipped, @@ -803,6 +914,7 @@ impl Notes { unclipped: self.unclipped, clipped_out: self.clipped_out, blank, + unadjusted, } } } @@ -810,6 +922,8 @@ impl Notes { struct Builder<'a, F> { h: &'a Header<'a>, records: &'a [Record<'a>], + /// The records as layers and groups (see [`tree`]). + tree: &'a [Item], /// Hidden layers come in, hidden. hidden: bool, max_alloc: u64, @@ -842,6 +956,10 @@ struct Builder<'a, F> { unclipped: Vec, /// Those records, in the order they were counted. unclip_log: Vec, + /// The records counted as adjustment layers the import applies that weren't applied. + unadjusted: Vec, + /// Those records, in the order they were counted. + unadjust_log: Vec, /// The records that came in as layers of the document (hidden ones too, with `hidden`): not left /// out, though a drawing for a merge that wasn't made counted them. kept: Vec, @@ -865,6 +983,14 @@ struct Builder<'a, F> { blank_log: Vec, /// How many times a merge was counted as not made because it needed more memory than allowed. squeezed: usize, + /// The adjustment layer whose own merge with the layers below it is being made: a layer mask of + /// its too large to read stops that merge, where one of another adjustment layer drawn in it + /// leaves that one out. + adjusting: Option, + /// Whether each record's stored transparency is 0 everywhere, once [`Self::clear`] has read it. + clear: Vec>>, + /// Whether each record's layer mask hides all of it, once [`Self::masked_out`] has read it. + masked_out: Vec>>, } impl [f32; 3]> Builder<'_, F> { @@ -922,7 +1048,7 @@ impl [f32; 3]> Builder<'_, F> { let h = self.h; let max_side = if h.psb { 300_000 } else { 30_000 }; let (w, rows) = match rec.content { - Content::Adjustment => return Ok(None), + Content::Adjustment(_) => return Ok(None), // A fill layer that stores no pixels (a shape layer stores its shape's; one that // doesn't, with only its vector mask, isn't drawn). Content::Solid(Some(paint)) if rec.color_over_canvas() => { @@ -993,6 +1119,210 @@ impl [f32; 3]> Builder<'_, F> { Ok(Some((i64::from(m.bounds.left), i64::from(m.bounds.top), img, read(m.default)))) } + /// Does record `i`'s layer mask, switched on, fit the memory allowed for reading it with + /// [`Self::mask`] beside `live` bytes of canvases held while it is read, and the copies of what + /// is below the pass-through groups being merged? `true` when it has none, and when its size is + /// damaged (reading it says so). + fn mask_fits(&self, i: usize, live: u64) -> Result { + let rec = self.record(i)?; + let Some(m) = rec.mask.filter(|m| !m.disabled) else { return Ok(true) }; + if !rec.channels.iter().any(|(c, _)| *c == -2) { + return Ok(true); + } + let (w, rows) = m.bounds.size(); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + if w > max_side || rows > max_side { + return Ok(true); + } + let bytes = (row_bytes(w, self.h.depth) as u64 + w as u64).saturating_mul(rows as u64); + Ok(bytes.saturating_add(live) <= self.room()) + } + + /// Does record `i` store pixels that are all fully transparent, so that it paints nothing? + /// Its transparency is read once. `false` when it stores none, or has no transparency, or its + /// transparency can't be read within the memory allowed or is damaged (drawing it says so); one + /// that didn't fit the memory allowed is read again the next time. + fn clear(&self, i: usize) -> Result { + if let Some(clear) = self.clear.get(i).and_then(Cell::get) { + return Ok(clear); + } + let rec = self.record(i)?; + let (w, rows) = rec.bounds.size(); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + let alpha = rec.channels.iter().find(|(c, _)| *c == -1).map(|(_, data)| data); + let clear = match alpha { + Some(data) if !rec.draws_nothing() && !rec.color_over_canvas() && w <= max_side && rows <= max_side => { + let (depth, row) = (self.h.depth, row_bytes(w, self.h.depth)); + let bytes = (row as u64).saturating_mul(rows as u64); + if bytes > self.room() { + return Ok(false); + } + // Not counted against the import's allowance: the transparency is read again, and + // counted, where the layer is drawn. + match layer_channel(data, rows, row, self.h.psb, depth) { + Ok(plane) => { + (0..rows).all(|y| plane.get(y * row..(y + 1) * row).is_some_and(|r| (0..w).all(|x| byte(sample(r, x, depth, false)) == 0))) + } + Err(_) => false, + } + } + _ => false, + }; + if let Some(c) = self.clear.get(i) { + c.set(Some(clear)); + } + Ok(clear) + } + + /// Does record `i` have a layer mask, switched on, that hides all of it? The mask is 0 over every + /// pixel that isn't fully transparent of the layers whose stored pixels show where it draws: a + /// layer's own, and a group's those of its layers, in the groups inside it too (every pixel of a + /// layer whose transparency can't be read). For an adjustment layer, a layer that stores no + /// pixels and a group with one of those in it, which can change pixels anywhere below them, it + /// is 0 everywhere, the value outside it included. The mask is read once. `false` when it has + /// none, or it can't be read within the memory allowed or is damaged (drawing it says so); a + /// `false` that a read skipped for lack of memory decided is worked out again the next time. + /// `group` says the record opens a group. + fn masked_out(&self, i: usize, group: bool) -> Result { + if let Some(out) = self.masked_out.get(i).and_then(Cell::get) { + return Ok(out); + } + let rec = self.record(i)?; + // The layers whose stored pixels show where it draws, when they all do. + let layers = if group { + match find_group(self.tree, i) { + Some(items) => { + let mut layers = vec![]; + self.painters(items, &mut layers)?.then_some(layers) + } + None => None, + } + } else { + (!rec.stores_nothing() && !matches!(rec.content, Content::Adjustment(_))).then(|| vec![i]) + }; + let outside = rec.mask.map_or(0, |m| if m.inverted { 255 - m.default } else { m.default }); + // Whether a read skipped for lack of memory decided it. + let mut squeezed = false; + let out = if (layers.is_none() && outside != 0) || !self.has_mask(Some(i))? { + false + } else if !self.mask_fits(i, 0)? { + squeezed = true; + false + } else { + // Not counted against the import's allowance: the mask is read again, and counted, where + // the layer is drawn or its opacity mask is made. + let spent = self.spent.get(); + let read = self.mask(i, false); + self.spent.set(spent); + match read { + // 0 everywhere hides all of anything. + Ok(Some((_, _, m, 0))) if m.pixels().all(|p| p.0[0] == 0) => true, + Ok(Some(mask)) => match &layers { + Some(layers) => { + let mut hides = true; + for &l in layers { + if !self.hides(i, l, &mask, &mut squeezed)? { + hides = false; + break; + } + } + hides + } + None => false, + }, + Ok(None) => false, + Err(_) => { + squeezed = true; + false + } + } + }; + if (out || !squeezed) + && let Some(c) = self.masked_out.get(i) + { + c.set(Some(out)); + } + Ok(out) + } + + /// Push onto `out` the layers in `items` (in the groups inside them too) that store pixels. + /// `false` when one of them can change or draw pixels where it stores none: an adjustment layer, + /// or a fill that stores no pixels. + fn painters(&self, items: &[Item], out: &mut Vec) -> Result { + for item in items { + match item { + Item::Layer(l) => { + let r = self.record(*l)?; + if r.covers_without_drawing() || r.color_over_canvas() || matches!(r.content, Content::Adjustment(_)) { + return Ok(false); + } + if !r.stores_nothing() { + out.push(*l); + } + } + Item::Group(_, children) => { + if !self.painters(children, out)? { + return Ok(false); + } + } + } + } + Ok(true) + } + + /// Does `mask`, record `i`'s layer mask read with [`Self::mask`], hide every pixel of layer `l` + /// that isn't fully transparent? Every pixel counts when `l`'s transparency can't be read beside + /// the mask; `squeezed` is set when that is for lack of memory. + fn hides(&self, i: usize, l: usize, mask: &(i64, i64, image::GrayImage, u8), squeezed: &mut bool) -> Result { + let (left, top, m, outside) = mask; + let (left, top, outside) = (*left, *top, *outside); + let (right, bottom) = (left + i64::from(m.width()), top + i64::from(m.height())); + let rec = self.record(l)?; + let b = rec.bounds; + let (bl, bt, br, bb) = (i64::from(b.left), i64::from(b.top), i64::from(b.right), i64::from(b.bottom)); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + let (w, rows) = b.size(); + // The sides are checked first: the row's size could overflow otherwise. + let fits = w <= max_side && rows <= max_side; + let row = if fits { row_bytes(w, self.h.depth) } else { 0 }; + // Its transparency, when it stores one that can be read beside the mask. Not counted against + // the import's allowance: it is read again, and counted, where the layer is drawn. + let alpha = match rec.channels.iter().find(|(c, _)| *c == -1) { + Some((_, data)) if fits && !rec.draws_nothing() && !rec.color_over_canvas() => { + if self.mask_fits(i, (row as u64).saturating_mul(rows as u64))? { + layer_channel(data, rows, row, self.h.psb, self.h.depth).ok() + } else { + *squeezed = true; + None + } + } + _ => None, + }; + let within = left <= bl && top <= bt && br <= right && bb <= bottom; + if outside != 0 && !within && alpha.is_none() { + return Ok(false); + } + // Its pixels the mask's value outside it can show, or only those under the mask. + let (x0, y0, x1, y1) = if outside != 0 { (bl, bt, br, bb) } else { (bl.max(left), bt.max(top), br.min(right), bb.min(bottom)) }; + for y in y0..y1 { + let line = match &alpha { + Some(plane) => match plane.get((y - bt) as usize * row..((y - bt) as usize + 1) * row) { + Some(r) => Some(r), + None => return Ok(false), + }, + None => None, + }; + for x in x0..x1 { + let under = (left..right).contains(&x) && (top..bottom).contains(&y); + let v = if under { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { outside }; + if v != 0 && line.is_none_or(|r| byte(sample(r, (x - bl) as usize, self.h.depth, false)) != 0) { + return Ok(false); + } + } + } + Ok(true) + } + /// Multiply `c`'s transparency by record `i`'s layer mask. fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; @@ -1058,8 +1388,14 @@ impl [f32; 3]> Builder<'_, F> { } self.refund(spent)?; // The merge doesn't fit: this layer and the next ones clipped to the same - // base come in as layers of their own. + // base come in as layers of their own; an adjustment layer, which would + // change more than its base, isn't applied. unclipped = true; + if self.adjustment(&body)?.is_some() { + self.squeezed += 1; + self.unadjust(i); + continue; + } self.unclip(i); out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false }); } @@ -1089,25 +1425,44 @@ impl [f32; 3]> Builder<'_, F> { #[allow(clippy::too_many_arguments)] fn clip(&mut self, out: &mut [Unit<'_>], b: usize, body: &Body<'_>, i: usize, name: &str, blend: Blend, opacity: f32) -> Result { let Some(u) = out.get(b) else { return Ok(true) }; - let (whole, undrawn, fill, base_opacity) = { + let (whole, undrawn, fill, base_opacity, base_adjusts, base_adjustment) = { let r = self.record(u.record)?; let layer = matches!(u.body, Body::Layer(_)); - (layer && r.covers_without_drawing(), layer && r.undrawn_shape(), r.fill, r.opacity) + // The base as a layer, or as the canvas of the layers already clipped to it. + let adjustment = (layer || u.clip.is_some()) && matches!(r.content, Content::Adjustment(_)); + (layer && r.covers_without_drawing(), layer && r.undrawn_shape(), r.fill, r.opacity, layer && r.adjust().is_some(), adjustment) }; // A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either. if undrawn && u.clip.is_none() { self.clip_out(i); return Ok(true); } - let layer = match self.draw_body(body, Some(i))? { - Drawn::Nothing => return Ok(true), - Drawn::TooLarge => return Ok(false), - Drawn::Canvas(c) => c, + // A clipped adjustment layer changes the merged canvas in place, through its layer mask. + let adjust = self.adjustment(body)?; + // Its layer mask too large to read needs more memory than allowed: it isn't applied, and the + // layers clipped above it still clip to the base. + if adjust.is_some() && !base_adjustment && !self.mask_fits(i, 0)? { + self.squeezed += 1; + self.unadjust(i); + return Ok(true); + } + let layer = match adjust { + Some(_) => Canvas::default(), + None => match self.draw_body(body, Some(i))? { + Drawn::Nothing => return Ok(true), + Drawn::TooLarge => return Ok(false), + Drawn::Canvas(c) => c, + }, }; let room = self.room(); let layer_bytes = 16 * layer.px.len() as u64; let Some(u) = out.get_mut(b) else { return Ok(true) }; if u.clip.is_none() { + // An adjustment layer that others are clipped to isn't applied. + if base_adjusts { + let record = u.record; + self.unadjust(record); + } let (canvas, clip) = if whole { (Canvas::default(), Clip::Whole) } else { @@ -1134,6 +1489,28 @@ impl [f32; 3]> Builder<'_, F> { u.opacity = base_opacity; } let Body::Merged(c) = &mut u.body else { return Ok(true) }; + if let Some(a) = adjust { + // Clipped to an adjustment layer, it would change the layers below that one: not applied. + if base_adjustment { + self.unadjust(i); + return Ok(true); + } + // The mask is read beside the merged canvas and the base's shape. + let shape = match &u.clip { + Some(Clip::Shape(s)) => 4 * s.len() as u64, + _ => 0, + }; + if !self.mask_fits(i, (16 * c.px.len() as u64).saturating_add(shape))? { + self.squeezed += 1; + self.unadjust(i); + return Ok(true); + } + let mask = self.mask(i, false)?; + adjust_onto(c, a, blend, opacity, mask.as_ref(), i); + u.name.push_str(" + "); + u.name.push_str(name); + return Ok(true); + } match &u.clip { Some(Clip::Shape(_)) => { if (20 * c.px.len() as u64).saturating_add(layer_bytes) > room { @@ -1191,7 +1568,8 @@ impl [f32; 3]> Builder<'_, F> { }; match content { Content::Type => self.notes.types += 1, - Content::Adjustment => self.notes.adjustments += 1, + // One the import applies is counted only where it isn't (see `unadjust`). + Content::Adjustment(None) => self.notes.adjustments += 1, // A fill drawn from neither its pixels nor its color. Content::Fill | Content::Solid(None) if empty => self.notes.fills += 1, Content::Solid(Some(_)) if empty && vector_mask => self.notes.fills += 1, @@ -1286,6 +1664,206 @@ impl [f32; 3]> Builder<'_, F> { } } + /// Count record `i` as an adjustment layer the import applies that wasn't applied (once). + fn unadjust(&mut self, i: usize) { + if let Some(s) = self.unadjusted.get_mut(i) + && !*s + { + *s = true; + self.notes.unadjusted += 1; + self.unadjust_log.push(i); + } + } + + /// The adjustment `body` applies: a layer record that is an adjustment layer the import applies. + fn adjustment(&self, body: &Body<'_>) -> Result, String> { + match body { + Body::Layer(i) => Ok(self.record(*i)?.adjust()), + _ => Ok(None), + } + } + + /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to + /// change what is below the group), those kept in the visible pass-through groups of `out` + /// included: from the first one with nothing that draws below it in `out`, as [`Self::leading`] + /// keeps them. A group whose layer mask hides all of it keeps none. + fn pending(&self, out: &[Unit<'_>], level: Level) -> Result, String> { + let (mut records, mut draws) = (vec![], false); + if level != Level::Pass { + return Ok(records); + } + // A hidden unit, kept with the hidden layers, or one at 0 opacity, changes nothing. + for u in out.iter().filter(|u| u.visible && u.opacity > 0.0) { + if self.adjustment(&u.body)?.is_some() { + records.push(u.record); + continue; + } + if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) + && (!draws || !records.is_empty()) + && !u.mask_of.map(|g| self.masked_out(g, true)).transpose()?.unwrap_or(false) + { + let (inner, inner_draws) = self.leading(items)?; + records.extend(inner); + draws |= inner_draws; + continue; + } + draws = draws || self.unit_draws(u)?; + } + Ok(records) + } + + /// Does unit `u` draw? An adjustment layer, a layer that draws nothing or whose pixels are all + /// transparent, a group of such layers, and a unit whose layer mask hides all of it, don't. + fn unit_draws(&self, u: &Unit<'_>) -> Result { + let draws = match &u.body { + Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, + Body::Group(_, items) => self.draws(items)?, + // Clipped layers merged with a base that has no pixels have none either. + Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), + }; + // A base merged with the layers clipped to it draws within its own pixels, or, when it covers + // the canvas without drawing, anywhere: its mask hides all of it as it hides the base (see + // `base_draws`). + let hidden = |m: usize| match &u.body { + Body::Layer(_) => self.masked_out(m, false), + Body::Group(..) => self.masked_out(m, true), + Body::Merged(_) => self.masked_out(m, matches!(self.record(m)?.divider, 1 | 2)), + }; + Ok(draws && !u.mask_of.map(hidden).transpose()?.unwrap_or(false)) + } + + /// The adjustment layers the import applies that a pass-through group with the layers `items` + /// keeps to change what is below it: from the first one with nothing that draws below it in the + /// group (hidden and clipped layers, other adjustment layers, layers and groups at 0 opacity, and + /// layers and groups that draw nothing aren't counted), it and every one above it, in the + /// pass-through groups inside it too; one at 0 opacity isn't kept. Also whether anything in + /// `items` draws. + fn leading(&self, items: &[Item]) -> Result<(Vec, bool), String> { + let (mut records, mut draws) = (vec![], false); + for (k, item) in items.iter().enumerate() { + let (i, r, children) = match item { + Item::Layer(i) => (*i, self.record(*i)?, None), + Item::Group(g, children) => (*g, self.record(*g)?, Some(children)), + }; + // A clipped one draws as part of the one it is clipped to. + if r.hidden || r.clipped { + continue; + } + let (clips, drawn) = self.base_draws(items, k)?; + // One in a mode VectorCraft lacks (an adjustment layer aside), or with a shallow knockout + // that cuts what is below it, is merged with the layers below it in the group, which + // takes the ones kept so far with them (see `merged`). + if (matches!(r.blend, Blend::Other(_)) && (children.is_some() || r.adjust().is_none())) || self.cuts(items, k, clips, drawn && draws)? { + records.clear(); + } + // One that layers are clipped to isn't kept, and a pass-through group they are clipped to + // is drawn alone (see `clip`). One at 0 opacity changes nothing (see `adjust_below`). + let keeps = !clips && r.opacity * r.fill > 0.0 && (!draws || !records.is_empty()); + match children { + None if r.adjust().is_some() && !clips => { + if keeps { + records.push(i); + } + } + // A pass-through group whose layer mask hides all of it draws and changes nothing. + Some(children) if r.blend == Blend::Pass && keeps && !self.masked_out(i, true)? => { + let (inner, inner_draws) = self.leading(children)?; + records.extend(inner); + draws |= inner_draws; + } + _ => draws |= drawn, + } + } + Ok((records, draws)) + } + + /// Does item `k` of `items`, a pass-through group's layers, take a shallow knockout that is merged + /// with the layers below it (see [`Self::knocks`])? Only one that `clips` nothing, is in the + /// Normal mode over visible layers in the Normal mode back to the last one merged for its mode, + /// and where it and something below it draw (`draws`). + fn cuts(&self, items: &[Item], k: usize, clips: bool, draws: bool) -> Result { + let record = |item: &Item| match item { + Item::Layer(i) | Item::Group(i, _) => self.record(*i), + }; + let Some(r) = items.get(k).map(record).transpose()? else { return Ok(false) }; + let normal = Blend::Mode(BlendMode::Normal); + if r.knockout != 1 || clips || !draws || r.blend != normal { + return Ok(false); + } + for below in items.get(..k).unwrap_or_default().iter().rev() { + let b = record(below)?; + if b.hidden || b.clipped { + continue; + } + match b.blend { + Blend::Other(_) if matches!(below, Item::Group(..)) || b.adjust().is_none() => break, + blend if blend != normal => return Ok(false), + _ => {} + } + } + Ok(true) + } + + /// Does anything in `items` draw: a visible layer or group that isn't clipped and draws (see + /// [`Self::base_draws`])? + fn draws(&self, items: &[Item]) -> Result { + for (k, item) in items.iter().enumerate() { + let r = match item { + Item::Layer(i) => self.record(*i)?, + Item::Group(g, _) => self.record(*g)?, + }; + if !r.hidden && !r.clipped && self.base_draws(items, k)?.1 { + return Ok(true); + } + } + Ok(false) + } + + /// For item `k` of `items`, visible and not clipped: whether visible layers are clipped to it, + /// and whether it draws, above 0 opacity: by its own pixels (a group's, those of its layers) + /// above 0 fill, or by those of the layers clipped to it that draw, which show in its pixels at + /// any fill, or over the canvas when it is a layer that covers it without drawing and that its + /// layer mask doesn't hide all of. + fn base_draws(&self, items: &[Item], k: usize) -> Result<(bool, bool), String> { + let Some(item) = items.get(k) else { return Ok((false, false)) }; + let (r, own) = self.pixels(item)?; + let covers = match item { + Item::Layer(i) => r.covers_without_drawing() && !self.masked_out(*i, false)?, + Item::Group(..) => false, + }; + let (mut clips, mut clips_draw) = (false, false); + for above in items.get(k + 1..).unwrap_or_default() { + let c = match above { + Item::Layer(i) => self.record(*i)?, + Item::Group(g, _) => self.record(*g)?, + }; + if !c.clipped { + break; + } + if c.hidden { + continue; + } + clips = true; + if !clips_draw && c.opacity * c.fill > 0.0 { + clips_draw = self.pixels(above)?.1; + } + } + let drawn = (r.fill > 0.0 && own) || (clips_draw && (covers || own)); + Ok((clips, r.opacity > 0.0 && drawn)) + } + + /// `item`'s record, and whether it has pixels of its own: a layer that draws, or a group with + /// something in it that draws (see [`Self::draws`]), that its layer mask doesn't hide all of. + fn pixels(&self, item: &Item) -> Result<(&Record<'_>, bool), String> { + Ok(match item { + Item::Layer(i) => { + let r = self.record(*i)?; + (r, !r.draws_nothing() && !self.clear(*i)? && !self.masked_out(*i, false)?) + } + Item::Group(g, children) => (self.record(*g)?, self.draws(children)? && !self.masked_out(*g, true)?), + }) + } + /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group /// the layers with a shallow knockout, merged with those below. fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result>, String> { @@ -1322,6 +1900,10 @@ impl [f32; 3]> Builder<'_, F> { continue; } Knocked::Merged(canvas) => { + // Adjustment layers kept below it in the group are merged with nothing to change. + for r in self.pending(&out, level)? { + self.unadjust(r); + } self.take_merge(&mut out, &u, canvas); if let Blend::Other(other) = u.blend && !self.notes.merged.contains(&other.label()) @@ -1350,42 +1932,25 @@ impl [f32; 3]> Builder<'_, F> { } } } + if self.adjustment(&u.body)?.is_some() { + self.adjust_below(&mut out, u, level)?; + continue; + } let Blend::Other(other) = u.blend else { out.push(u); continue; }; // A merge that can't be made counts nothing its groups would have counted. let saved = self.saved(); + let pending = self.pending(&out, level)?; let outer = self.try_from_here(); - let made = match out.as_mut_slice() { - // Onto the previous merge alone: composited onto its canvas, in place. - [prev] if prev.is_merge() => { - let mut acc = match &mut prev.body { - Body::Merged(c) => Some(std::mem::take(c)), - _ => None, - }; - let made = self.composite(&mut acc, &u); - if let Body::Merged(c) = &mut prev.body { - *c = acc.unwrap_or_default(); - } - if made? { - prev.name.push_str(" + "); - prev.name.push_str(&u.name); - true - } else { - false - } - } - _ => match self.merge(&out, &u)? { - Some(canvas) => { - self.take_merge(&mut out, &u, canvas); - true - } - None => false, - }, - }; + let made = self.merge_into(&mut out, &u)?; self.tried(outer, made)?; if made { + // Adjustment layers kept below it in the group are merged with nothing to change. + for r in pending { + self.unadjust(r); + } if !self.notes.merged.contains(&other.label()) { self.notes.merged.push(other.label()); } @@ -1400,9 +1965,97 @@ impl [f32; 3]> Builder<'_, F> { Ok(out) } + /// `out` replaced by one layer, the merge of its visible units with `top` (see + /// [`Self::take_merge`]). `false` when the canvas would need more memory than allowed. + fn merge_into<'i>(&mut self, out: &mut Vec>, top: &Unit<'_>) -> Result { + match out.as_mut_slice() { + // Onto the previous merge alone: composited onto its canvas, in place. + [prev] if prev.is_merge() => { + let mut acc = match &mut prev.body { + Body::Merged(c) => Some(std::mem::take(c)), + _ => None, + }; + let made = self.composite(&mut acc, top); + if let Body::Merged(c) = &mut prev.body { + *c = acc.unwrap_or_default(); + } + if made? { + prev.name.push_str(" + "); + prev.name.push_str(&top.name); + Ok(true) + } else { + Ok(false) + } + } + _ => match self.merge(out, top)? { + Some(canvas) => { + self.take_merge(out, top, canvas); + Ok(true) + } + None => Ok(false), + }, + } + } + + /// Adjustment layer `u` (one the import applies), at `level`, merged with the visible units + /// `out` below it in its list: they become one layer, adjusted. A hidden one would need the + /// merge and is left out. With nothing visible below it that draws (other adjustment layers and + /// layers and groups that draw nothing or are at 0 opacity don't count), or at 0 opacity, it + /// changes nothing + /// and comes in as nothing, except in a pass-through group, where it is kept to change what is + /// below the group when the group is drawn onto it; there, once one is kept (in the group or in + /// a pass-through group in it), the ones above it are kept too, in order. One that layers are clipped to, and one whose merge needs more memory + /// than allowed, isn't applied, and is counted. + fn adjust_below<'i>(&mut self, out: &mut Vec>, u: Unit<'i>, level: Level) -> Result<(), String> { + if !u.visible { + self.skip(u.record); + return Ok(()); + } + // One that layers are clipped to, kept as a layer because they drew nothing or their merge + // didn't fit, isn't applied. + if u.base { + self.unadjust(u.record); + return Ok(()); + } + if u.opacity <= 0.0 { + return Ok(()); + } + // A unit that draws nothing has nothing to change. + let mut below = false; + for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { + below = below || self.unit_draws(b)?; + } + // Kept below it in the group, or in a pass-through group below it there. + let pending = !self.pending(out, level)?.is_empty(); + if level == Level::Pass && (pending || !below) { + out.push(u); + return Ok(()); + } + if !below { + return Ok(()); + } + let saved = self.saved(); + let outer = self.try_from_here(); + let adjusting = self.adjusting.replace(u.record); + let made = self.merge_into(out, &u); + self.adjusting = adjusting; + let made = made?; + self.tried(outer, made)?; + if !made { + self.restore(saved)?; + self.squeezed += 1; + self.unadjust(u.record); + } else if let Blend::Other(other) = u.blend + && !self.notes.merged.contains(&other.label()) + { + self.notes.merged.push(other.label()); + } + Ok(()) + } + /// The counts as they are, for [`Self::restore`]. fn saved(&self) -> Counts { - self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()) + self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len(), self.unadjust_log.len()) } /// The counts as they were before a merge that couldn't be made, the bytes it spent counted as @@ -1442,6 +2095,12 @@ impl [f32; 3]> Builder<'_, F> { self.notes.clipped_out = self.notes.clipped_out.saturating_sub(1); } } + for i in self.unadjust_log.split_off(c.unadjusted) { + if let Some(s) = self.unadjusted.get_mut(i) { + *s = false; + self.notes.unadjusted = self.notes.unadjusted.saturating_sub(1); + } + } self.notes.merged.truncate(c.merged); self.notes.unmerged = c.unmerged; Ok(()) @@ -1563,7 +2222,7 @@ impl [f32; 3]> Builder<'_, F> { Body::Layer(i) => { let rec = self.record(*i)?; match rec.content { - Content::Adjustment => continue, + Content::Adjustment(_) => continue, Content::Solid(Some(_)) if rec.color_over_canvas() => [0, 0, i64::from(self.h.width), i64::from(self.h.height)], _ => { let (w, h) = rec.bounds.size(); @@ -1643,6 +2302,28 @@ impl [f32; 3]> Builder<'_, F> { } return Ok(true); } + // An adjustment layer changes `acc` where it is, through its layer mask. + if let Some(a) = self.adjustment(&u.body)? { + if let Some(c) = acc.as_mut() { + let mask = match u.mask_of { + // A layer mask too large to read beside the canvas needs more memory than + // allowed: the adjustment isn't applied, and the rest of the merge goes on. + Some(i) if !self.mask_fits(i, 16 * c.px.len() as u64)? => { + // The adjustment's own merge isn't made then. + if self.adjusting == Some(u.record) { + return Ok(false); + } + self.squeezed += 1; + self.unadjust(u.record); + return Ok(true); + } + Some(i) => self.mask(i, false)?, + None => None, + }; + adjust_onto(c, a, u.blend, u.opacity, mask.as_ref(), u.record); + } + return Ok(true); + } let c = match self.draw_body(&u.body, u.mask_of)? { Drawn::Nothing => return Ok(true), Drawn::Canvas(c) => c, @@ -1760,6 +2441,12 @@ impl [f32; 3]> Builder<'_, F> { if let Some(k) = self.kept.get_mut(u.record) { *k = true; } + // An adjustment layer kept in a pass-through group with nothing below it in the group: the + // layers below the group aren't changed by it. + if self.adjustment(&u.body)?.is_some() { + self.unadjust(u.record); + return Ok(None); + } let children = match &u.body { Body::Layer(i) => match self.image(*i)? { Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], @@ -1870,6 +2557,32 @@ fn fade(after: &mut Canvas, before: Option<&Canvas>, opacity: f32, mask: Option< } } +/// `c` changed by adjustment `a` (of record `record`): at each pixel, the adjusted color is +/// composited over the color as it was in `blend`, at `opacity` times the value of `mask` (as +/// [`fade`] takes it) there. The transparency of each pixel stays as it was. +fn adjust_onto(c: &mut Canvas, a: Adjust, blend: Blend, opacity: f32, mask: Option<&(i64, i64, image::GrayImage, u8)>, record: usize) { + let width = c.width.max(1); + let opacity = opacity.clamp(0.0, 1.0); + for (k, p) in c.px.iter_mut().enumerate() { + if p[3] <= 0.0 { + continue; + } + let (x, y) = (c.left + (k % width) as i64, c.top + (k / width) as i64); + let m = mask.map_or(255, |(left, top, m, default)| { + let inside = (*left..*left + i64::from(m.width())).contains(&x) && (*top..*top + i64::from(m.height())).contains(&y); + if inside { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { *default } + }); + let t = coverage(blend, opacity * f32::from(m) / 255.0, x, y, record); + if t <= 0.0 { + continue; + } + let rgb = [p[0], p[1], p[2]]; + let [r, g, b] = a.apply(rgb); + let mixed = over(blend, [rgb[0], rgb[1], rgb[2], 1.0], [r, g, b, t]); + *p = [mixed[0], mixed[1], mixed[2], p[3]]; + } +} + /// `src` (of record `record`) at `opacity` composited onto `acc` (nothing when `None`) in `blend`, /// on a canvas covering both (`acc` itself when it covers `src`; a larger one is counted with /// `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a larger @@ -2008,6 +2721,7 @@ pub(super) fn import( let mut b = Builder { h: &h, records: &records, + tree: &items, hidden, max_alloc, held: 0, @@ -2027,6 +2741,8 @@ pub(super) fn import( clipped_out_log: vec![], unclipped: vec![false; records.len()], unclip_log: vec![], + unadjusted: vec![false; records.len()], + unadjust_log: vec![], kept: vec![false; records.len()], spent: Cell::new(0), wasted: Cell::new(0), @@ -2036,6 +2752,9 @@ pub(super) fn import( laid_blank: vec![false; records.len()], blank_log: vec![], squeezed: 0, + adjusting: None, + clear: vec![Cell::new(None); records.len()], + masked_out: vec![Cell::new(None); records.len()], }; let layers = b.list(&items, Level::Top)?; // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't. diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index d5dccfd662..8660eee992 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -18,6 +18,8 @@ struct L { rect: [i32; 4], /// Red, green, blue and alpha, the same for every pixel. rgba: [u8; 4], + /// The alpha of each pixel, in place of `rgba`'s, stored raw. + alpha: Option>, blend: &'static [u8; 4], opacity: u8, clipped: bool, @@ -40,6 +42,7 @@ fn layer(name: &'static str, rect: [i32; 4], rgba: [u8; 4]) -> L { name, rect, rgba, + alpha: None, blend: b"norm", opacity: 255, clipped: false, @@ -96,10 +99,15 @@ fn predict(row: &[u8], depth: u16) -> Vec { } } -/// A channel of `n` samples of `v` (in 32 bits, `v` / 255 as a float) at `depth`, raw, zipped -/// (with prediction when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`. +/// One sample of `v` at `depth` (in 32 bits, `v` / 255 as a float). +fn sample_of(v: u8, depth: u16) -> Vec { + if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] } +} + +/// A channel of `n` samples of `v` (see [`sample_of`]) at `depth`, raw, zipped (with prediction +/// when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`. fn channel(v: u8, n: usize, width: usize, depth: u16, rle: bool, psb: bool, zip: Option) -> Vec { - let sample = if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] }; + let sample = sample_of(v, depth); let row: Vec = std::iter::repeat_n(sample.as_slice(), width).flatten().copied().collect(); if let Some(predicted) = zip { let rows = n.checked_div(width).unwrap_or(0); @@ -151,11 +159,17 @@ fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec { .filter(|_| !l.bare) .map(|&(id, v)| (id, channel(v, w * h, w, depth, rle, psb, l.zip))) .collect(); + if let (Some(pixels), Some((_, d))) = (&l.alpha, channels.first_mut()) { + *d = vec![0, 0]; + for &p in pixels { + d.extend(sample_of(p, depth)); + } + } let mut mask = vec![]; if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask { let mut d = vec![0, 0]; for &p in pixels { - d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + d.extend(sample_of(p, depth)); } channels.push((-2, d)); for v in [mt, ml, mb, mr] { @@ -391,9 +405,9 @@ fn zipped_and_32_bit_layers_read() { /// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman. #[test] fn names_without_a_unicode_name_read_as_mac_roman() { - let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) }; + let l = L { legacy: Some(b"Caf\x8E\xCA\xD2Old\xD3\xDB"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) }; let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({})); - assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}"); + assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café\u{a0}“Old”€", "{r}"); } #[test] @@ -1201,6 +1215,790 @@ fn layers_clipped_to_an_adjustment_layer_show_over_the_canvas() { assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{r}"); } +/// An adjustment layer of key `key` with `data`, storing no pixels. +fn adjustment(name: &'static str, key: &[u8; 4], data: &[u8]) -> L { + L { blocks: vec![(*key, data.to_vec())], ..layer(name, [0, 0, 0, 0], [0; 4]) } +} + +/// The colors of a 1-pixel-high layer's image, left to right. +fn row_of(s: &Session, l: &Node) -> Vec<[u8; 4]> { + let px = image_of(s, l).1; + (0..px.width()).map(|x| px.get_pixel(x, 0).0).collect() +} + +/// Invert, Threshold and Posterize adjustment layers merge with the visible layers below them, which +/// they change; the layers above stay apart. Invert turns each value `v` into `255 − v`; Threshold +/// at 128 makes a pixel white when its luminance is above 128 and black at or below it; Posterize at +/// 4 levels maps each channel to the nearest of 0, 85, 170 and 255. +#[test] +fn invert_threshold_and_posterize_merge_with_the_layers_below() { + let top = layer("Top", [0, 0, 1, 1], [1, 2, 3, 255]); + for (depth, psb) in [(8, false), (16, false), (8, true), (16, true)] { + let layers = [ + layer("Dark", [0, 0, 1, 1], [10, 20, 30, 255]), + layer("Light", [0, 1, 1, 2], [200, 150, 100, 128]), + adjustment("Invert", b"nvrt", &[]), + top.clone(), + ]; + let (s, r) = open(&file(2, 1, &layers, depth, false, psb), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Dark + Light + Invert", "Top"], "{depth} {psb}: {r}"); + assert_eq!(r["warnings"], json!([]), "{depth} {psb}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255], [55, 105, 155, 128]], "{depth} {psb}: transparency stays"); + assert_eq!(row_of(&s, &d.layers[1]), [[1, 2, 3, 255]], "{depth} {psb}: the layer above isn't changed"); + } + let grays = [ + layer("128", [0, 0, 1, 1], [128, 128, 128, 255]), + layer("129", [0, 1, 1, 2], [129, 129, 129, 255]), + layer("Light", [0, 2, 1, 3], [200, 150, 100, 255]), + layer("Dark", [0, 3, 1, 4], [10, 20, 30, 255]), + ]; + let layers = [&grays[..], &[adjustment("Threshold", b"thrs", &[0, 128, 0, 0])][..]].concat(); + let (s, r) = open(&file(4, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["128 + 129 + Light + Dark + Threshold"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 0, 255]]); + let layers = + [layer("A", [0, 0, 1, 1], [42, 43, 128, 255]), layer("B", [0, 1, 1, 2], [212, 213, 0, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0])]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["A + B + Posterize"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[0, 85, 170, 255], [170, 255, 0, 255]]); +} + +/// An adjustment layer's opacity, layer mask and blend mode decide how much of the adjusted color +/// replaces the color below. +#[test] +fn an_adjustment_layer_takes_its_opacity_mask_and_blend_mode() { + let black = || layer("Black", [0, 0, 1, 2], [0, 0, 0, 255]); + let half = L { opacity: 128, ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(2, 1, &[black(), half], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[128, 128, 128, 255]; 2], "{r}"); + // Black in the mask leaves the first pixel as it was; outside, the mask's default (white) applies it. + let masked = L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(2, 1, &[black(), masked], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255]], "{r}"); + assert!(d.layers[0].extras().mask.is_none(), "the mask is spent on the merge"); + // A disabled mask applies it everywhere. + let off = L { mask: Some(([0, 0, 1, 1], 255, 2, vec![0])), ..adjustment("Invert", b"nvrt", &[]) }; + let (s, _) = open(&file(2, 1, &[black(), off], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]; 2]); + // Multiply: the inverted color (55, 155, 205) multiplies the color below. + let multiply = L { blend: b"mul ", ..adjustment("Invert", b"nvrt", &[]) }; + let (s, _) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [200, 100, 50, 255]), multiply], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[43, 61, 40, 255]]); + // In a mode VectorCraft lacks, the warnings name the mode, as for other layers merged for it. + let dodge = L { blend: b"lddg", ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), dodge], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}"); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(r["warnings"], json!([merged])); +} + +/// Clipped to a layer, an adjustment layer changes only that layer and the layers clipped to it. +#[test] +fn a_clipped_adjustment_layer_changes_only_its_base() { + let layers = [ + layer("Other", [0, 1, 1, 2], [10, 10, 10, 255]), + layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Other", "Base + Invert"], "{r}"); + assert_eq!(r["warnings"], json!([])); + assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 10, 10, 255]], vec![[55, 255, 255, 255]])); + // Over a layer clipped to the same base, and only inside the base's shape. + let layers = [ + layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) }, + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Base + Photo + Invert"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 0, 255]]); + // Clipped to another adjustment layer, it isn't applied: the layers keep their colors. + let layers = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + adjustment("Curves", b"curv", &[0; 4]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) }, + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Curves + Photo"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 20, 30, 255]], vec![[0, 0, 255, 255]])); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // Its layer mask isn't read then: one too large to read doesn't stop the file opening. + let mut masked = layers; + masked[3].mask = Some(([0, 0, 1, 40_000], 0, 0, vec![200])); + let (s, r) = open(&file(1, 1, &masked, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Curves + Photo"], "{r}"); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // An Invert layer that a layer drawing nothing is clipped to isn't applied either. + let layers = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Empty", [0, 0, 0, 0], [0; 4]) }, + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"])); +} + +/// A hidden adjustment layer changes nothing and is left out, with or without the hidden layers; one +/// with nothing below it, or in an isolated group with nothing below it there, changes nothing. +#[test] +fn hidden_and_lone_adjustment_layers_change_nothing() { + for hidden in [false, true] { + let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), L { hidden: true, ..adjustment("Invert", b"nvrt", &[]) }]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden})); + let d = &s.doc().unwrap().doc; + assert_eq!((d.layers.iter().map(|l| name(l)).collect::>(), &r["warnings"]), (vec!["Under"], &json!([HIDDEN_1])), "{hidden}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); + } + let (s, r) = open(&file(1, 1, &[adjustment("Invert", b"nvrt", &[]), layer("Top", [0, 0, 1, 1], [10, 20, 30, 255])], 8, false, false), json!({})); + assert_eq!((s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect::>(), &r["warnings"]), (vec!["Top"], &json!([]))); + let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Isolated", b"norm")]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!((d.layers.iter().map(|l| name(l)).collect::>(), &r["warnings"]), (vec!["Under", "Isolated"], &json!([]))); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); +} + +/// In a pass-through group with nothing below it in the group, an adjustment layer changes what is +/// below the group when the group is merged; when the group comes in as layers, it isn't applied. +#[test] +fn an_adjustment_layer_in_a_pass_through_group_changes_what_is_below_the_group() { + let layers = |dodge: bool| { + let mut l = vec![layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass")]; + if dodge { + l.push(L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }); + } + l + }; + let (s, r) = open(&file(1, 1, &layers(true), 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]]); + let (s, r) = open(&file(1, 1, &layers(false), 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Folder"], "{r}"); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"])); + // Two at the bottom of the group both change what is below it, in order: inverted, then + // posterized to 4 levels (without the Invert the color would posterize to black). + let stacked = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &stacked, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}"); + // One above a layer of the group, with one kept below that layer, is kept too: the group draws + // them in order over what is below it. + let between = [ + layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + layer("Top", [0, 1, 1, 2], [100, 100, 100, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(2, 1, &between, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255], [85, 85, 85, 255]], "{r}"); + // Another adjustment layer below it in the group draws nothing, so it still changes what is + // below the group. + let over_curves = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Curves", b"curv", &[0; 4]), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &over_curves, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}"); + // One kept in a pass-through group inside the group keeps the ones above it too: inverted, then + // posterized to 4 levels. + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}"); + // Without the merge, the group comes in as layers and both are counted as not applied. + let (s, r) = open(&file(1, 1, &nested[..7], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Folder"], "{r}"); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // Merged in the group with a layer in a mode VectorCraft lacks, it has nothing to change. + let inside = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &inside, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!((names, &r["warnings"]), (vec!["Under", "Folder"], &json!(["1 adjustment layer was not applied", merged])), "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); +} + +/// The layer of a pass-through group's sublayers whose name ends with `end`. +fn sublayer<'d>(folder: &'d Node, end: &str) -> &'d Node { + let children = folder.children().map(Vec::as_slice).unwrap_or_default(); + let names: Vec<&str> = children.iter().map(|c| name(c)).collect(); + children.iter().find(|c| name(c).ends_with(end)).unwrap_or_else(|| panic!("no sublayer ending with {end} in {names:?}")) +} + +/// An adjustment layer that changes nothing, in a hidden pass-through group or at 0 opacity or 0 +/// fill, keeps no adjustment layer above it in the group from merging with the layers below it: +/// the gray 100 posterizes to 85. +#[test] +fn adjustment_layers_that_change_nothing_hold_none_back() { + let invert = |opacity: u8, fill: u8| { + let mut l = L { opacity, ..adjustment("Invert", b"nvrt", &[]) }; + l.blocks.push((*b"iOpa", vec![fill])); + l + }; + let cases = [("hidden group", true, invert(255, 255)), ("0 opacity", false, invert(0, 255)), ("0 fill", false, invert(255, 0))]; + for (what, hidden, invert) in cases { + let layers = [ + group_end(), + group_end(), + invert, + L { hidden, ..group("Inner", b"pass") }, + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Folder"], "{what}: {r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Photo + Posterize")), [[85, 85, 85, 255]], "{what}: {r}"); + } +} + +/// A layer that stores no pixels draws nothing: an adjustment layer above it in a pass-through group, +/// directly or in a pass-through group inside it, still changes what is below the group. +#[test] +fn an_adjustment_layer_over_layers_that_draw_nothing_changes_what_is_below_the_group() { + let empty = || layer("Empty", [0, 0, 0, 0], [0; 4]); + let direct = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + empty(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); + // Inverted in the inner group, then posterized to 4 levels. + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + empty(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); + // Nor does a group of such layers, in any mode, or a layer at 0 opacity: below them, directly + // or in the inner group, Invert and Posterize still change what is below the outer group. + let mut no_fill = layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]); + no_fill.blocks.push((*b"iOpa", vec![0])); + let photo = || layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]); + let below: [(&str, Vec); 5] = [ + ("empty group", vec![group_end(), empty(), group("Empty", b"norm")]), + ("empty pass-through group", vec![group_end(), empty(), group("Empty", b"pass")]), + ("0 opacity", vec![L { opacity: 0, ..layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]) }]), + ("0 fill in a group", vec![group_end(), no_fill, group("Empty", b"norm")]), + ("group clipped to an empty layer", vec![empty(), group_end(), photo(), L { clipped: true, ..group("Clipped", b"norm") }]), + ]; + for (what, nothing) in below { + let direct = [ + &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end()][..], + ¬hing, + &[adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }], + ] + .concat(); + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{what}: {r}"); + let nested = [ + &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), group_end()][..], + ¬hing, + &[ + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ], + ] + .concat(); + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{what}: {r}"); + } +} + +/// Layers clipped to a layer at 0 fill, or to an adjustment layer, draw: an adjustment layer above +/// them in a pass-through group merges with them and is applied. +#[test] +fn an_adjustment_layer_over_clipped_layers_merges_with_them() { + let mut clear = layer("Base", [0, 0, 1, 1], [0, 0, 0, 255]); + clear.blocks.push((*b"iOpa", vec![0])); + let photo = || L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) }; + let layers = [ + group_end(), + group_end(), + clear, + photo(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(r["warnings"], json!([merged]), "{r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}"); + // The same with a group at 0 fill as the base. + let mut clear_group = group("Base", b"norm"); + clear_group.blocks.push((*b"iOpa", vec![0])); + let layers = [ + group_end(), + group_end(), + group_end(), + layer("Black", [0, 0, 1, 1], [0, 0, 0, 255]), + clear_group, + photo(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(r["warnings"], json!([merged]), "{r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}"); + // Clipped to an Invert layer, which isn't applied then, the photo shows over the canvas, and + // Posterize merges with it: the gray 100 posterizes to 85. + let layers = [ + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]) }, + group("Folder", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{r}"); +} + +/// Invert, Threshold and Posterize data that can't be read is not applied, with a warning: a level +/// out of range, data too short, or a second adjustment block on the layer. +#[test] +fn adjustment_data_that_cant_be_read_isnt_applied() { + let mut twice = adjustment("Twice", b"nvrt", &[]); + twice.blocks.push((*b"post", vec![0, 4, 0, 0])); + let mut apart = adjustment("Apart", b"nvrt", &[]); + apart.blocks.extend([(*b"SoCo", vec![]), (*b"post", vec![0, 4, 0, 0])]); + let cases = [ + adjustment("Level 0", b"thrs", &[0, 0, 0, 0]), + adjustment("Level 256", b"thrs", &[1, 0, 0, 0]), + adjustment("No level", b"thrs", &[]), + adjustment("No padding", b"thrs", &[0, 128]), + adjustment("No padding", b"post", &[0, 4]), + adjustment("1 level", b"post", &[0, 1, 0, 0]), + adjustment("256 levels", b"post", &[1, 0, 0, 0]), + twice, + apart, + ]; + for bad in cases { + let what = bad.name; + let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), bad], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under"], "{what}: {r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]], "{what}"); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]), "{what}"); + } + // The highest level and count are read. + let under = |c: u8| layer("Under", [0, 0, 1, 1], [c, c, c, 255]); + let (s, r) = open(&file(1, 1, &[under(254), adjustment("Max", b"thrs", &[0, 255, 0, 0])], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[0, 0, 0, 255]], "{r}"); + let (s, r) = open(&file(1, 1, &[under(7), adjustment("Max", b"post", &[0, 255, 0, 0])], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[7, 7, 7, 255]], "{r}"); +} + +/// An adjustment layer whose merge needs more memory than allowed isn't applied: the layers below +/// it stay as they are, with a warning. +#[test] +fn an_adjustment_merge_past_the_memory_allowed_isnt_applied() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]), layer("Beside", [2, 2, 4, 4], [1, 2, 3, 255]), adjustment("Invert", b"nvrt", &[])]; + let f = file(4, 4, &layers, 8, false, false); + // Each 2 × 2 layer fits 128 bytes; the 4 × 4 canvas of both doesn't. + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Beside"]); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under + Beside + Invert"]); + assert!(warnings.is_empty(), "{warnings:?}"); + // Clipped: the base's canvas with its shape doesn't fit 300 bytes, so the adjustment is left + // out rather than applied to everything below. + let layers = [layer("Base", [0, 0, 4, 4], [10, 20, 30, 255]), L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 300, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Base"]); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + // A layer clipped to an Invert layer whose merge doesn't fit comes in unclipped, and the Invert + // layer isn't applied to the layers below it. + let layers = [ + layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Photo", [0, 0, 4, 4], [1, 2, 3, 255]) }, + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Photo"], "{warnings:?}"); + assert!(warnings.iter().any(|w| w == "1 adjustment layer was not applied"), "{warnings:?}"); +} + +/// An adjustment layer whose layer mask is too large for the memory allowed isn't applied, merged +/// with the layers below it or clipped to one, and the file still opens with its layers. +#[test] +fn an_adjustment_mask_past_the_memory_allowed_isnt_applied() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + // The 100 × 100 mask takes more than 128 bytes; the 1-pixel layer below it doesn't. + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![0; 10_000])), ..adjustment("Invert", b"nvrt", &[]) }; + for clipped in [false, true] { + let f = file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), masked(clipped)], 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under"], "{clipped}: {warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}"); + // With the memory for it, the mask's black leaves the layer as it was. + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under + Invert"], "{clipped}: {warnings:?}"); + assert!(warnings.is_empty(), "{clipped}: {warnings:?}"); + } +} + +/// An adjustment layer's mask is read beside the canvases it changes: a 100 × 1 mask fits 256 bytes +/// alone, but not beside a 6 × 1 canvas, so the layer isn't applied. With the memory for both, it is. +#[test] +fn an_adjustment_mask_counts_the_canvas_it_changes() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 1, 100], 255, 0, vec![255; 100])), ..adjustment("Invert", b"nvrt", &[]) }; + for clipped in [false, true] { + let f = file(6, 1, &[layer("Under", [0, 0, 1, 6], [10, 20, 30, 255]), masked(clipped)], 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 256, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under"], "{clipped}: {warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}"); + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under + Invert"], "{clipped}: {warnings:?}"); + assert!(warnings.is_empty(), "{clipped}: {warnings:?}"); + } +} + +/// An adjustment layer whose mask is too large to read is left out without stopping the clip or the +/// merge around it: a layer clipped above it still clips to the base, and a layer in a mode +/// VectorCraft lacks above a pass-through group holding it still merges in its mode. +#[test] +fn an_adjustment_mask_too_large_leaves_the_clip_and_merge_around_it() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![255; 10_000])), ..adjustment("Invert", b"nvrt", &[]) }; + let layers = [layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), masked(true), L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) }]; + let (doc, warnings) = psdlayers::import(&file(2, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Base + Photo"], "{warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + // Gray 100 under Linear Dodge's gray 20 gives gray 120. + let layers = [ + layer("Under", [0, 0, 1, 1], [100, 100, 100, 255]), + group_end(), + masked(false), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [20, 20, 20, 255]) }, + ]; + let (doc, warnings) = psdlayers::import(&file(1, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{warnings:?}"); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(warnings, ["1 adjustment layer was not applied", merged]); + let Some([c]) = doc.layers[0].children().map(Vec::as_slice) else { panic!("the merged layer holds one image") }; + let NodeKind::Image(img) = &c.kind else { panic!("the merged layer holds an image") }; + let px = craft_image_codecs::decode(&doc.images[&img.key].bytes).unwrap().to_rgba8(); + assert_eq!(px, [120, 120, 120, 255]); +} + +/// A layer merged in a pass-through group for its mode or its knockout takes the adjustment layers +/// kept below it with it: an adjustment layer above that group in an outer pass-through group then +/// merges with it, and the gray 100 posterizes to 85. +#[test] +fn an_adjustment_layer_above_a_group_whose_kept_ones_merged_is_applied() { + let tops = [ + ("Linear Dodge", vec![L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]) }]), + ("knockout", vec![layer("Photo", [0, 0, 1, 1], [50, 50, 50, 255]), knockout(layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]), 1, 255)]), + ]; + for (what, top) in tops { + let layers = [ + &[group_end(), group_end(), adjustment("Invert", b"nvrt", &[])][..], + &top, + &[group("Inner", b"pass"), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass")], + ] + .concat(); + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{what}: {r}"); + assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{what}: {r}"); + } +} + +/// An adjustment layer in a pass-through group, over a layer drawn below that group in an outer +/// pass-through group, isn't kept to change what is below the outer group: a layer merged above +/// them for its mode merges it applied, and the import doesn't count it as not applied. The gray +/// 100 inverts to 155. +#[test] +fn an_adjustment_layer_in_a_group_over_a_drawn_layer_merges_applied() { + let layers = [ + group_end(), + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Top")), [[155, 155, 155, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); +} + +/// A layer whose pixels are all transparent draws nothing: an adjustment layer above it in a +/// pass-through group, directly or in a pass-through group inside it, still changes what is below +/// the group. +#[test] +fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() { + let clear = || layer("Clear", [0, 0, 1, 1], [50, 50, 50, 0]); + let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }; + let direct = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + clear(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{r}"); + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + clear(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}"); +} + +/// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in +/// a pass-through group still changes what is below the group, and a shallow knockout hidden that +/// way merges nothing, so the adjustment layers below it stay kept. A layer's mask hides all of it +/// when it hides each of its pixels that isn't fully transparent, and a group's when it hides each +/// such pixel of the group's layers, whatever the mask's value elsewhere; a layer hidden that way +/// hides the layers clipped to it too. The layers in a pass-through group hidden that way don't +/// count as drawing below an adjustment layer above the group. +#[test] +fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() { + let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l }; + let under = || layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]); + let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 2], [0, 0, 0, 255]) }; + let photo = || layer("Photo", [0, 0, 1, 2], [100, 100, 100, 255]); + let inverted = [[245, 235, 225, 255], [245, 235, 225, 255]]; + let masked_layer = [under(), group_end(), black(photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + // A mask over all of the layer's pixels hides it whatever its value outside them. + let white_outside = L { mask: Some(([0, 0, 1, 2], 255, 0, vec![0, 0])), ..photo() }; + let covered_layer = [under(), group_end(), white_outside, adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + let masked_group = [ + under(), + group_end(), + group_end(), + photo(), + black(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + let knockout_cut = knockout(black(layer("Cut", [0, 0, 1, 1], [0, 0, 255, 255])), 1, 255); + let masked_knockout = [ + under(), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + knockout_cut, + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + // A knockout whose mask hides each pixel it doesn't leave transparent. + let half = L { alpha: Some(vec![255, 0]), mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 255])), ..layer("Cut", [0, 0, 1, 2], [0, 0, 255, 255]) }; + let mut transparent_knockout = masked_knockout.clone(); + transparent_knockout[5] = knockout(half, 1, 255); + // A pass-through group its mask hides, below Invert in a pass-through group, with a layer drawn + // above that group, under Posterize. + let masked_pass = [ + under(), + group_end(), + group_end(), + group_end(), + photo(), + black(group("Hidden", b"pass")), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + // Invert in a pass-through group its mask hides keeps nothing above that group: Posterize + // merges with the layer below it, as with no such group. + let masked_invert = [ + under(), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + black(group("Hidden", b"pass")), + layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + // A mask over only the pixels that aren't fully transparent, white outside it. + let corner = |l: L| L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..l }; + let half_photo = || L { alpha: Some(vec![255, 0]), ..photo() }; + let corner_layer = [under(), group_end(), corner(half_photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + let corner_group = [ + under(), + group_end(), + group_end(), + half_photo(), + corner(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + // The same mask over a group with a pixel drawn outside it: the group draws there. + let drawn_group = [ + under(), + group_end(), + group_end(), + photo(), + corner(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + // A layer its mask hides, with a layer clipped to it. + let clipped_base = [ + under(), + group_end(), + black(photo()), + L { clipped: true, ..layer("Red", [0, 0, 1, 2], [200, 0, 0, 255]) }, + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + let cases = [ + ("layer", &masked_layer[..], inverted), + ("covered layer", &covered_layer[..], inverted), + ("group", &masked_group[..], inverted), + ("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), + ("transparent knockout", &transparent_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), + ("pass-through group", &masked_pass[..], [[0, 0, 85, 255], [255, 255, 255, 255]]), + ("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 85, 255], [10, 20, 30, 255]]), + ("layer covered where it draws", &corner_layer[..], inverted), + ("group covered where it draws", &corner_group[..], inverted), + ("group drawn outside its mask", &drawn_group[..], [[10, 20, 30, 255], [155, 155, 155, 255]]), + ("clipped base", &clipped_base[..], inverted), + ]; + let rows = |layers: &[L]| { + let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({})); + row_of(&s, &s.doc().unwrap().doc.layers[0]) + }; + let got: Vec<_> = cases.iter().map(|(what, layers, _)| (*what, rows(layers))).collect(); + let want: Vec<_> = cases.iter().map(|(what, _, want)| (*what, want.to_vec())).collect(); + assert_eq!(got, want); +} + +/// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. +#[test] +fn damaged_adjustment_layers_never_panic() { + let layers = [ + layer("A", [0, 0, 2, 2], [255, 0, 0, 255]), + L { mask: Some(([0, 0, 1, 1], 0, 0, vec![200])), ..adjustment("Invert", b"nvrt", &[]) }, + L { clipped: true, ..adjustment("Threshold", b"thrs", &[0, 128, 0, 0]) }, + adjustment("Posterize", b"post", &[0, 3, 0, 0]), + ]; + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let good = file(2, 2, &layers, 8, false, false); + assert!(psdlayers::import(&good, true, 1 << 30, cms).unwrap().is_some()); + for i in 0..good.len() { + for v in [0, 1, 0x7f, 0x80, 0xff] { + let mut f = good.clone(); + f[i] = v; + let _ = psdlayers::import(&f, true, 1 << 30, cms); + let _ = psdlayers::import(&f, false, 64, cms); + } + } + for n in 0..good.len() { + let _ = psdlayers::import(&good[..n], true, 1 << 30, cms); + } +} + /// Each blend mode VectorCraft lacks merges with the layer below by its formula, from the public /// descriptions: /// (Vivid Light, Pin Light, Hard Mix, Darker and Lighter Color) and @@ -1449,6 +2247,12 @@ fn damaged_layers_never_panic() { assert!(psdlayers::import(&file(8, 8, &many[..16], 8, false, false), false, 512, cms).unwrap().is_some()); let e = psdlayers::import(&file(8, 8, &many, 8, false, false), false, 512, cms).err(); assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}"); + // Looking through those layers' transparency for pixels that draw, below an adjustment layer, + // takes nothing from the allowance. + let mut clear: Vec = (0..16).map(|_| layer("x", [0, 0, 8, 8], [1, 2, 3, 0])).collect(); + clear.push(adjustment("Invert", b"nvrt", &[])); + let opened = psdlayers::import(&file(8, 8, &clear, 8, false, false), false, 512, cms); + assert!(opened.as_ref().is_ok_and(Option::is_some), "{:?}", opened.err()); } /// A layer in a mode VectorCraft lacks above a pass-through group merges with the group's layers diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 7a56932aed..37f4b132b5 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -863,6 +863,78 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { } } +/// Unembed leaves a clipping mask released or edited in the document as it is, with a path and with +/// a folder, for a plain image and for a distorted one: no clip group of the file's clipping path is +/// put back or nested inside the edited mask. Every case runs, and the test names each one that +/// fails. +#[test] +fn unembed_keeps_a_released_or_edited_clipping_mask() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-mask"); + let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources())); + let cases = ["release", "move"] + .into_iter() + .flat_map(|edit| [false, true].into_iter().flat_map(move |distort| [(edit, distort, false), (edit, distort, true)])); + let failed: Vec<_> = cases + .filter(|&(edit, distort, folder)| { + std::panic::catch_unwind(|| unembed_mask_case(&dir.join(format!("{edit}-{distort}-{folder}")), &data, edit, distort, folder)).is_err() + }) + .collect(); + assert!(failed.is_empty(), "failed: {failed:?}"); +} + +/// One case of [`unembed_keeps_a_released_or_edited_clipping_mask`]: the clipping mask of a placed +/// PSD file's image released or moved (`edit`), the image or the clip group then distorted with +/// `distort`, and the image unembedded into `out`. +fn unembed_mask_case(out: &std::path::Path, data: &str, edit: &str, distort: bool, folder: bool) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + if edit == "release" { + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.clippingMask.release", &json!({})).unwrap(); + } else { + let Some(NodeKind::Group { children, .. }) = s.doc().unwrap().doc.node(group).map(|n| &n.kind) else { panic!("a clip group") }; + let mask = children[0].id; + s.execute("select.set", &json!({"ids": [mask.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + } + if distort { + let target = if edit == "release" { image } else { group }; + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image(), "{edit}, folder: {folder}: distorted"); + } + let parent = |s: &Session| s.doc().unwrap().doc.parent_of(image); + let before = (parent(&s), parent(&s).and_then(|p| s.doc().unwrap().doc.node(p).cloned())); + std::fs::create_dir_all(out).unwrap(); + if folder { + s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap(); + } else { + s.execute("links.unembed", &json!({"id": image.0, "path": out.join("cut")})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "{edit}, folder: {folder}: linked to the file written"); + assert_eq!(parent(&s), before.0, "{edit}, folder: {folder}: the image stays where it was"); + let after = before.0.and_then(|p| d.node(p)); + match (edit, after.map(|n| &n.kind), before.1.as_ref().map(|n| &n.kind)) { + // Released: the image is in no clip group, as before. + ("release", Some(NodeKind::Group { clip, .. }), _) => assert!(!clip, "folder: {folder}: the released mask came back"), + ("release", _, _) => {} + // Moved: the same clip group of the moved path holds just the image. + (_, Some(NodeKind::Group { children: a, clip: true }), Some(NodeKind::Group { children: b, clip: true })) => { + assert_eq!(a.len(), 2, "{edit}, folder: {folder}: a clip group was nested inside the edited mask"); + let path = |c: &std::sync::Arc| match &c.kind { + NodeKind::Path { path, .. } => path.anchors().map(|(_, _, a)| [a.p.x, a.p.y]).collect::>(), + _ => vec![], + }; + assert_eq!((path(&a[0]), a[1].id), (path(&b[0]), image), "{edit}, folder: {folder}: the clipping mask"); + } + other => panic!("{edit}, folder: {folder}: {other:?}"), + } +} + /// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a /// text chunk within the size limit that reads as a path gives one back. #[test] diff --git a/crates/engine/src/cmd/flare.rs b/crates/engine/src/cmd/flare.rs index 8871ddf921..17a566e29c 100644 --- a/crates/engine/src/cmd/flare.rs +++ b/crates/engine/src/cmd/flare.rs @@ -65,12 +65,14 @@ fn settings_of(p: &Value, cmd: &str) -> Result { }; let rays = count_or(p, "rays", 15, cmd)?.min(50); let rings = count_or(p, "rings", 10, cmd)?.min(50); + // The end point is given whole or not at all: a lone `x2` or `y2` is refused. let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) { (Some(x), Some(y)) => Point::new(x, y), - _ => { + (None, None) => { let a = f64_or(p, "direction", 45.0).to_radians(); finite_end(c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0), cmd)? } + _ => Point::new(f64_req(p, "x2", cmd)?, f64_req(p, "y2", cmd)?), }; let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed }); if let Some(r) = ring_seed { diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index b238dd865a..548e5fade2 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", has_doc, set_point ), @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Delete Freeform Point", [], None, - "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}", + "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", has_doc, delete_point ), @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Add Freeform Line", [], None, - "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}", + "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {line}", has_doc, add_line ), @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Split Freeform Line", [], None, - "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}", + "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", has_doc, split_line ), @@ -64,7 +64,7 @@ pub fn specs() -> Vec { "Select Freeform Point", [], None, - "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}", + "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxies show the Live Paint Bucket's colors): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}", has_doc, select_point ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Freeform Gradient", [], None, - "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}", + "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxies show the Live Paint Bucket's colors) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}", has_doc, get ), @@ -81,6 +81,14 @@ pub fn specs() -> Vec { } const NOT_FREEFORM: &str = "the paint is not a freeform gradient (apply one with paint.editGradient {kind: \"freeform\"})"; +const BUCKET_NOT_FREEFORM: &str = "the Live Paint Bucket's colors have no freeform points (give ids, id or item to edit an object's)"; +const BUCKET_NO_POINTS: &str = "the Live Paint Bucket's colors have no freeform points"; + +/// The error of `paint.freeform.get` and `paint.freeform.selectPoint` when the active proxy shows no freeform gradient: +/// while the Live Paint Bucket paints, the proxies show its colors, which have none. +fn no_proxy_freeform(s: &Session) -> &'static str { + if s.bucket_paints() { BUCKET_NO_POINTS } else { NOT_FREEFORM } +} impl Session { /// The selected freeform point (`paint.freeform.selectPoint`), while the gradient it was @@ -179,6 +187,14 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result { /// as one undo step; returns what it returned for the first. An unplaced gradient gets the /// automatic points it shows first, and the stops follow the points' colours. fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result) -> Result { + // While the Live Paint Bucket paints, the proxies show its colors, which have no freeform points + // (paint.freeform.get finds none): an edit that names no target is refused. A bad `aligned` or + // `target` is refused first, as it is without the bucket. + if super::paint::for_bucket(s, p) { + super::appearance::aligned(p, cmd)?; + super::appearance::targets_contents(p)?; + return Err(bad(cmd, BUCKET_NOT_FREEFORM)); + } let item = item_target(s, p, cmd)?; let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?; let item = item.of_kind(s, !stroke); @@ -331,7 +347,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result { Some(Value::Null) => None, Some(v) => { let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?; - let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, NOT_FREEFORM))?; + let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s)))?; check_index(&f, i).map_err(|e| bad(C, e))?; Some(i) } @@ -343,7 +359,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result { fn get(s: &mut Session, p: &Value) -> Result { const C: &str = "paint.freeform.get"; let stroke = switch_or(p, "stroke", !s.fill_active, C)?; - let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, NOT_FREEFORM))?; + let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s)))?; let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None }; let mut v = vectorcraft_tools::params::freeform_json(&f); v["selected"] = json!(selected); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 3b295a1805..d0ed27ca8a 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -9611,6 +9611,29 @@ fn appearance_commands_given_the_axes_or_legend_group_edit_its_lines_and_labels( } } +/// Aligned rows copied to `to` given the Legend group, whose labels have the same rows, go to `to` in every label. +#[test] +fn aligned_copies_given_the_legend_group_go_to_to_when_its_labels_have_the_same_rows() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let labels = |s: &Session| -> Vec { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + group(&n, "Legend").children().unwrap().iter().map(|c| (*c.appearance).clone()).collect() + }; + let legend = group(s.doc().unwrap().doc.node(id).unwrap(), "Legend").id; + s.execute("appearance.addFill", &json!({"ids": [legend.0]})).unwrap(); + s.execute("appearance.addStroke", &json!({"ids": [legend.0]})).unwrap(); + let was = labels(&s); + assert!(was.len() >= 2 && was.iter().all(|a| *a == was[0]) && was[0].items.len() >= 2, "{was:?}"); + let top = was[0].items.len() - 1; + s.execute("appearance.duplicateItem", &json!({"ids": [legend.0], "index": top, "to": 0, "aligned": true})).unwrap(); + for a in labels(&s) { + assert_eq!(a.items.len(), was[0].items.len() + 1); + assert_eq!(a.items[0], was[0].items[top], "the copy is at the bottom"); + } +} + /// A row index given the Axes group, whose lines and labels have different rows, is refused unless it is `aligned`, a row /// of the backmost member's stack: then the members that share that row change, the labels keep theirs, and the graph /// keeps the change when it is drawn again. diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 4d562a76e7..ecbfa760bb 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -20,7 +20,6 @@ use serde_json::{Map, Value, json}; use vectorcraft_color::{Color, GradientPaint, Paint}; use vectorcraft_doc::{Appearance, Node, NodeId, TextStyleDef}; -use super::clipboard::SwatchChoices; use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, color_value, has_doc, ids_param, index_opt, ok, point_param, str_param}; use crate::Clipboard; @@ -713,7 +712,7 @@ pub fn specs() -> Vec { "Use Library Item", [], None, - "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", + "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", has_doc, use_item ), @@ -1353,12 +1352,13 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { if clip.nodes.is_empty() { return Err(damaged()); } - let choices = SwatchChoices::default(); - // The pattern's name in the document, worked out on a copy: nothing to add is no edit. - let mut probe = (*s.doc()?.doc).clone(); - let imported = clip.import_into(&mut probe, &choices, false)?; - let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str()); - let target = renamed.unwrap_or(&name).to_string(); + // The pattern's name in the document, worked out on a copy: nothing to add is no edit. A global + // or spot color the pattern's art links to keeps the library's color, as Add to Swatches brings + // a library pattern's colors. + let current = s.doc()?.doc.clone(); + let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip)?; + drop(current); + let target = super::patternlib::imported_name(&imported, &name); let paint = vectorcraft_doc::pattern::pattern_paint(&target); // A pattern the document holds without a swatch (an imported SVG's) gets one. let has_swatch = diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index fccff66c0c..29da4d0524 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds no clipping path, and the clip group becomes a plain group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds no clipping path, and the clip group becomes a plain group. A clipping mask released, edited or made in the document stays as it is, in either case. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -1264,7 +1264,31 @@ fn warped(path: &PathData, map: &Homography) -> Option { /// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); /// with `also` (a file's path and the content shown), so do the images outside the layer tree that /// show that content. -fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { +fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { + install_with(d, ids, read, force, also, false) +} + +/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it +/// has a clipping path (`held`): a clipping mask released, edited or made in the document stays as +/// it is, and only a clip group of the old file's own clipping path follows the file written. +fn unembed_clip(to: ClipTo, held: bool) -> ClipTo { + match to { + ClipTo::Nest(_) => ClipTo::Keep, + ClipTo::File(_) if !held => ClipTo::Keep, + to => to, + } +} + +/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`]. +fn install_with( + d: &mut Document, + ids: &[NodeId], + (link, img): FileRead, + force: Option, + also: Option<(&str, &str)>, + unembed: bool, +) -> Result<()> { + let keep = |to: ClipTo, held: bool| if unembed { unembed_clip(to, held) } else { to }; let new_pt = super::place::pt_per_px(img.ppi); let mut clips = vec![]; let nested = nested_ids(d, ids); @@ -1290,7 +1314,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio _ => None, }; let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); - return (n, clip); + return (n, keep(clip, held.is_some())); } if let NodeKind::Image(im) = &mut n.kind { let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; @@ -1300,7 +1324,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio None => (super::place::pt_per_px(None), None), }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); - clip = clip_to(im.xf, old_clip, c, &img, xf, held); + clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some()); (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); } (n, clip) @@ -1315,7 +1339,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio }; let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule)); if let Some(n) = d.node_mut(*id) { - clips.push((*id, refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))))); + let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); + clips.push((*id, keep(clip, held.is_some()))); } continue; } @@ -1326,7 +1351,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio // Placement Options' clip, else the clipping path of a DCS file (read again with its // plates) or of a PSD or PSB file. let old_clip = d.images.get(&im.key).and_then(file_clip); - clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); + let held = clip_path_of(d, *id); + clips.push((*id, keep(clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, held), held.is_some()))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { @@ -2829,7 +2855,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { write_file(&path, &bytes)?; let read = (link_info(&path, &bytes), img); drop(doc); - s.edit("Unembed", |d, _| editing_brush_art(d, |d| install(d, &[id], read, Some(Preserve::Bounds), None)))?; + s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?; Ok(json!({ "id": id.0, "path": path })) } @@ -2896,7 +2922,7 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re drop(doc); let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); let edited = s.edit("Unembed", |d, _| { - editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None))) + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true))) }); if let Err(e) = edited { remove_written(&written); diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index fd0aece164..b2d857a464 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -12,7 +12,7 @@ use vectorcraft_geom::shapes::CornerKind; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, Vec2}; use vectorcraft_render::effects; -use super::edit::{duplicate_in, outermost, selected_roots, selected_roots_to_transform}; +use super::edit::{duplicate_beside, outermost, selected_roots, selected_roots_to_transform}; use super::opacitymask::percent; use super::{ CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_multi, has_selection, diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0bc08c748e..9082850dff 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Transform", [], None, - "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", + "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints), drawBehind?: bool (with copy: in Draw Behind, view.drawMode, each copy goes directly below its original instead of above it, as the Selection and Direct Selection tools' Alt-drags send; default false)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", has_doc, transform ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index f86d777e71..536dcf9c98 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -1,7 +1,7 @@ use super::align::choice; use super::{ Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad, - bool_or, check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param, + bool_or, check_numbers, check_switches, duplicate_beside, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param, selected_roots_to_transform, }; @@ -91,12 +91,22 @@ pub(crate) fn transform_node(n: &mut Node, xf: Affine, sc: Scaling, objects: boo /// `anchors` (`ids` being the selection): with anchors selected with Direct Selection and no /// copy, only those anchors transform, their handles with them, and the objects selected whole. pub(crate) fn apply_transform(s: &mut Session, label: &str, ids: Vec, xf: Affine, p: &Value, anchors: bool) -> Result { - apply_transform_moving_guides(s, label, ids, xf, p, anchors, None) + apply_transform_moving_guides(s, label, ids, xf, p, anchors, Placing::default()) } -/// [`apply_transform`], with the selected ruler guides moved by `guides` instead of by the +/// Where [`apply_transform_moving_guides`] puts the selected ruler guides and the copies. +#[derive(Clone, Copy, Default)] +struct Placing { + /// The selected ruler guides move by this instead of by the transform's translation. + guides: Option, + /// Each copy goes directly below its original instead of above it. + below: bool, +} + +/// [`apply_transform`], with the selected ruler guides moved by `placing.guides` instead of by the /// translation `xf` when given (a nudge along a turned Constrain Angle moves the art along it and -/// the guides along the page's axes). +/// the guides along the page's axes), and with each copy directly below its original with +/// `placing.below`. fn apply_transform_moving_guides( s: &mut Session, label: &str, @@ -104,8 +114,9 @@ fn apply_transform_moving_guides( xf: Affine, p: &Value, anchors: bool, - guides: Option, + placing: Placing, ) -> Result { + let Placing { guides, below } = placing; let copy = bool_or(p, "copy", false); let areas = bool_or(p, "typeAreas", false); let objects = transforms_objects(p); @@ -138,7 +149,7 @@ fn apply_transform_moving_guides( } else if none || (!copy && xf == Affine::IDENTITY) { if copy { vec![] } else { ids } } else { - let kept = if copy { preview_copies(s, &ids, with_guides)? } else { None }; + let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None }; s.edit(label, |d, sel| { let targets = match &kept { // The document becomes the snapshot with the kept copies, untransformed, and the @@ -155,7 +166,7 @@ fn apply_transform_moving_guides( } else { None }; - let new_ids = duplicate_in(d, sel, &ids, Affine::IDENTITY)?; + let new_ids = duplicate_beside(d, sel, &ids, Affine::IDENTITY, below)?; if let Some(copies) = guide_copies { sel.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect(); } @@ -212,11 +223,12 @@ fn apply_transform_moving_guides( /// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction /// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot /// back first). These are the copies the interaction keeps when they were made of that snapshot for -/// the same `roots`; otherwise this copies `roots` with [`duplicate_in`] in a clone of the snapshot, -/// untransformed, and the interaction keeps that clone. It returns `None` outside an interaction, +/// the same `roots` on the same side (`below`: directly below each original); otherwise this copies +/// `roots` with [`duplicate_beside`] in a clone of the snapshot, untransformed, and the interaction +/// keeps that clone. It returns `None` outside an interaction, /// and when the document is no longer the snapshot, as for a command run in a typing session or a /// script batch after an earlier edit there: the command then copies the current document. -pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: bool) -> Result>> { +pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: bool, below: bool) -> Result>> { let st = s.doc_mut()?; let Some(it) = &mut st.interaction else { return Ok(None) }; if !Arc::ptr_eq(&st.doc, &it.doc) { @@ -226,19 +238,20 @@ pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: boo if let Some(k) = &it.copies && Arc::ptr_eq(&k.from, &it.doc) && k.roots == roots + && k.below == below && (k.selection.guides.is_empty() != has_guide_copies) { return Ok(Some(k.clone())); } let mut doc = it.doc.clone(); let mut selection = st.selection.clone(); - let ids = duplicate_in(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY)?; + let ids = duplicate_beside(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY, below)?; if has_guide_copies { let d = Arc::make_mut(&mut doc); let copies: Vec<_> = st.selection.guides.iter().filter_map(|&i| d.ruler_guide(i)).collect(); selection.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect(); } - let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), doc, selection, ids }); + let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), below, doc, selection, ids }); it.copies = Some(k.clone()); Ok(Some(k)) } @@ -256,7 +269,9 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool { pub(super) fn transform(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?; - check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?; + check_switches(p, &["anchors", "releaseOutside", "interpolate", "drawBehind"], "object.transform")?; + // An Alt-drag copy in Draw Behind goes directly below its original. + let below = bool_or(p, "drawBehind", false) && bool_or(p, "copy", false) && s.draw_mode == crate::DrawMode::Behind; let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?; // An object selected in a symbol instance's art stays where the symbol puts it: the selection // is left as it is, and the reply's warning goes to the status bar. @@ -280,7 +295,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result { if grouped { s.begin_named_undo_group(None); } - let r = apply_transform(s, "Transform", ids, m, p, anchors); + let r = apply_transform_moving_guides(s, "Transform", ids, m, p, anchors, Placing { guides: None, below }); let released = match &r { Ok(_) if !moved.is_empty() => crate::cmd::shaper::release_outside(s, &moved), _ => Ok(false), @@ -358,7 +373,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { return ok(); } } - apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Some(Vec2::new(gx, gy))) + apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Placing { guides: Some(Vec2::new(gx, gy)), below: false }) } pub(super) fn about(o: Point, a: Affine) -> Affine { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b94a45e4f5..6666a1d7a3 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -373,16 +373,25 @@ impl DocState { } } +/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick? +fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool { + t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET) +} + impl Session { + /// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)? + pub(crate) fn lent_by_bucket(&self) -> bool { + self.lender.as_deref().is_some_and(works_for_bucket) + } + /// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the /// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while /// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a /// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the /// sample its click takes before it switches back to the bucket. pub fn bucket_paints(&self) -> bool { - let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET); // A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it. - self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket) + self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket() } /// The tool the active tool's armed one-shot pick switches back to after its click diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 96b9e51f99..1793f17d5c 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -199,14 +199,11 @@ pub fn specs() -> Vec { // ---------- helpers ---------- -/// Number param that also accepts strings like `"10 pt"`. +/// Number param that also accepts a string when all of it is a number (`"10"`, not `"10abc"`). pub(crate) fn num_param(p: &Value, key: &str) -> Option { match p.get(key)? { Value::Number(n) => n.as_f64(), - Value::String(s) => { - let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect(); - t.parse().ok() - } + Value::String(s) => whole_number(s), _ => None, } .filter(|v: &f64| v.is_finite()) diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index e4b6d810a6..d464be5d6f 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Replace Pattern Art", [], None, - "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", + "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}", can_replace_pattern_art, pattern_replace_art ), @@ -244,10 +244,15 @@ fn ids_json(ids: &[NodeId]) -> Value { json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) } +/// The outermost objects among `ids` (layers left out), else the selected ones. An id that names +/// no object is an error, so the command never acts on the other ids alone. fn roots(s: &Session, p: &Value, cmd: &str) -> Result> { match ids_param(p, "ids", cmd)? { Some(ids) => { let st = s.doc()?; + if let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_none()) { + return Err(bad(cmd, format!("no such object id {}", id.0))); + } let mut sel = Selection::default(); sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer()))); Ok(outermost(&st.doc, sel.in_paint_order(&st.doc))) diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 97351a27a2..64342b21dd 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -85,15 +85,29 @@ pub fn swatch_source(w: &Swatch) -> Option> { library_doc(b.id).filter(|d| d.pattern(pattern).is_some()) } +/// Swatches as (the swatch's name in a library, its name in a document). +pub(crate) type SwatchNames = Vec<(String, String)>; + /// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art /// painted with it does: the same pattern there already is used, and a name another pattern or /// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for -/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out. +/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out, +/// and the swatches `d` had that the art took under another name than its own, in the same form. /// A global or spot color whose name `d` gives another color comes in under a free name, as Add -/// to Swatches adds such a color, so that the pattern keeps the library's colors. -pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> { +/// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors +/// merge instead when that reuses a pattern of `d` that keeping them would add again +/// ([`probe_import`]). +pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> { + let gathered = gather(lib, name); let had: std::collections::HashSet = d.swatches_iter().map(|w| w.name.clone()).collect(); - let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?; + // Without a color to merge or a pattern to reuse, the document is not copied. + let imported = if !gathered.swatches.is_empty() && has_candidate(d, lib, name) { + let (_, probed, imported) = probe_import(d, lib, name, &gathered)?; + *d = probed; + imported + } else { + gathered.import_into(d, &SwatchChoices::add_all(), false)? + }; let from = |to: &str| { let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str()); renamed.unwrap_or(to).to_string() @@ -103,7 +117,14 @@ pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(St .filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. })) .map(|w| (from(&w.name), w.name.clone())) .collect(); - Ok((imported_name(&imported, name), added)) + let reused = imported + .renamed + .iter() + .filter(|r| r["kind"] == "swatch") + .filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string()))) + .filter(|(_, to)| had.contains(to)) + .collect(); + Ok((imported_name(&imported, name), added, reused)) } /// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied. @@ -112,17 +133,29 @@ fn gather(lib: &Document, name: &str) -> Clipboard { Clipboard::gather(lib, vec![user]) } +/// The names in `lib` of the swatches that pattern `name` of `lib` brings with its art. +pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::HashSet { + gather(lib, name).swatches.into_iter().map(|w| w.name).collect() +} + +/// The names in `lib` of pattern `name` and of the patterns its art brings. +pub(crate) fn brought_patterns(lib: &Document, name: &str) -> std::collections::HashSet { + gather(lib, name).patterns.into_iter().map(|p| p.name).collect() +} + /// The name pattern `name` has in the document `imported` went into. -fn imported_name(imported: &Imported, name: &str) -> String { +pub(crate) fn imported_name(imported: &Imported, name: &str) -> String { let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str()); renamed.unwrap_or(name).to_string() } /// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding -/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as -/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted -/// with, is imported into a copy of `d`, so that those resources are compared too. -pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option { +/// anything to `d` → its name in `d`, and the swatches of `d` that the art takes under another +/// name than its own, as [`import`] lists them. A pattern whose art uses no other resource is +/// compared as [`existing_pattern`] does. One whose art uses other resources, such as a pattern it +/// is painted with, is imported into a copy of `d` as [`probe_import`] does, so that those +/// resources are compared too. +pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<(String, SwatchNames)> { let gathered = gather(lib, name); let only_pattern = gathered.patterns.len() == 1 && gathered.symbols.is_empty() @@ -131,23 +164,58 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio && gathered.char_styles.is_empty() && gathered.para_styles.is_empty() && gathered.brushes.is_empty() - && gathered.images.is_empty(); + && gathered.images.is_empty() + && gathered.graph_designs.is_empty(); if only_pattern { - return existing_pattern(d, lib, name); + return existing_pattern(d, lib, name).map(|target| (target, vec![])); } - // Importing reuses only a pattern under that name or a numbered copy of it with the same tile - // options and as many art objects; without one, the document is not copied. - let def = lib.pattern(name)?; + // Without a pattern to reuse, the document is not copied. + if !has_candidate(d, lib, name) { + return None; + } + let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?; + if imported.added != 0 { + return None; + } + let took = imported + .renamed + .iter() + .filter(|r| r["kind"] == "swatch") + .filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string()))) + .filter(|(_, to)| d.swatches_iter().any(|w| w.name == *to)) + .collect(); + Some((imported_name(&imported, name), took)) +} + +/// Whether `d` has a pattern that importing pattern `name` of `lib` can reuse: one under that name +/// or a numbered copy of it with the same tile options and as many art objects. +pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool { + let Some(def) = lib.pattern(name) else { return false }; let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; let copy = |n: &str| { n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit())) }; - if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) { - return None; + d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) +} + +/// Import `gathered`, which paints with pattern `name` of `lib`, into a copy of `d` → the swatch +/// choices used, the copy and what the import did. A global or spot color whose name `d` gives +/// another color comes in under a free name (Add). Those colors merge instead when Add would add +/// the pattern again while merging reuses a pattern of `d`: such a pattern has its art linked to +/// the document's own colors of those names, as pasting with Merge, or adding it from a library +/// before, leaves it. +pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: &Clipboard) -> Result<(SwatchChoices, Document, Imported)> { + let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some(); + let mut with_add = d.clone(); + let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?; + if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) { + let mut merged = d.clone(); + let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?; + if reused(&found) { + return Ok((SwatchChoices::default(), merged, found)); + } } - let mut probe = d.clone(); - let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?; - (imported.added == 0).then(|| imported_name(&imported, name)) + Ok((SwatchChoices::add_all(), with_add, added)) } /// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under diff --git a/crates/engine/src/cmd/place/rtf.rs b/crates/engine/src/cmd/place/rtf.rs index 5af9519521..f9282abd5d 100644 --- a/crates/engine/src/cmd/place/rtf.rs +++ b/crates/engine/src/cmd/place/rtf.rs @@ -651,8 +651,8 @@ mod tests { let s = read(concat!(r"{\rtf1\ansi\uc1 caf\u233?\uc2 \u", "8364", r"\'80\'80 \uc1\u-10179?\u-8704? end\'93q\'94}")); assert_eq!(text_of(&s), "café€ 😀 end“q”"); assert_eq!(text_of(&read(r"{\rtf1\uc1\u233\bin1 ?X}")), "éX", "binary data is one fallback character"); - let mac = read(r"{\rtf1\mac \'8e\'a5}"); - assert_eq!(text_of(&mac), "é•", "Mac Roman"); + let mac = read(r"{\rtf1\mac \'8e\'ca\'a5\'db\'de}"); + assert_eq!(text_of(&mac), "é\u{a0}•€fi", "Mac Roman"); } #[test] diff --git a/crates/engine/src/cmd/place/text.rs b/crates/engine/src/cmd/place/text.rs index 78261a8804..06ab1af83f 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -185,20 +185,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char { /// Byte `b` of Mac Roman. pub(in crate::cmd) fn mac_roman(b: u8) -> char { - const HIGH: [char; 128] = [ - 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // - 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // - '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', // - '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', // - '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', // - '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', // - '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', // - '\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', - ]; - match b { - 0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), - _ => char::from(b), - } + craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b) } /// `text` with its line breaks (CR LF, CR or LF) as paragraph breaks, cleaned up as `o` says: @@ -344,7 +331,7 @@ mod tests { let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() }; assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é"); let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() }; - assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€"); + assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xCA, 0xA5, 0xDB, 0xDE, 0xF0], mac), "“q”é\u{a0}•€fi\u{f8ff}"); } /// The other character sets decode by their Encoding Standard decoders: the platform matters diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index b0d37a1d61..29ead30e52 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -272,17 +272,84 @@ impl Line { } fn push(&mut self, id: NodeId, m: &GlyphMatch) { - // A gap, past the tracking, wider than half a space before the glyph is spaces the - // outlines left no shape for. Each space takes the tracking too. + self.push_joined(id, m, None); + } + + /// For each of `ms`'s glyphs, the distance along the line to the next when untracked type sets + /// them with no spaces (their advances and pair kerning), and when it sets one space between + /// them (the glyph's own advance plus a space where type draws no such layout), taking the + /// characters laid out from `budget`; `None` when the budget is short or type does not draw + /// every glyph without spaces. + fn pair_steps(&self, ms: &[GlyphMatch], system_layout: bool, budget: &mut usize) -> Option> { + *budget = budget.checked_sub(ms.len().saturating_mul(3))?; let dir = self.dir(); - let gap = (m.origin - self.end).dot(dir) - self.tracking_pt(); - // Tracking tighter than a space's width gives each space a negative advance. - let space = space_advance(&self.face) * self.scale + self.tracking_pt(); - let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 }; - if spaces.is_finite() && spaces > 0.5 { - let n = (spaces.round() as usize).clamp(1, 64); - self.text.extend(std::iter::repeat_n(' ', n)); + let mut bare = self.clone(); + bare.tracking = 0.0; + let mut origins = |text: String| -> Vec { + bare.text = text; + let t = bare.probe(system_layout); + let lay = vectorcraft_text::layout(FontDb::global(), &t); + lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect() + }; + let joined = origins(ms.iter().map(|m| m.ch).collect()); + if joined.len() != ms.len() { + return None; } + let spaced = origins(ms.iter().map(|m| m.ch.to_string()).collect::>().join(" ")); + let space = space_advance(&self.face) * self.scale; + let spaced_ok = spaced.len() == ms.len(); + Some( + ms.iter() + .enumerate() + .zip(joined.windows(2)) + .map(|((i, m), p)| { + let own = m.face.advance(m.gid) * m.scale + space; + let apart = match (spaced_ok, spaced.get(i), spaced.get(i + 1)) { + (true, Some(a), Some(b)) => (*b - *a).dot(dir), + _ => own, + }; + ((p[1] - p[0]).dot(dir), apart) + }) + .collect(), + ) + } + + /// [`Line::push`], with `steps` the distances [`Line::pair_steps`] gives for the pair of the + /// line's last glyph and `m`. With `steps`, a gap reads as spaces only when they fit it better + /// than the joined pair does, as when the tracking is measured, however narrow the gap is. + fn push_joined(&mut self, id: NodeId, m: &GlyphMatch, steps: Option<(f64, f64)>) { + // Without `steps`, a gap, past the tracking, wider than half a space before the glyph is + // spaces the outlines left no shape for. Each space takes the tracking too. + let dir = self.dir(); + let tr = self.tracking_pt(); + let gap = (m.origin - self.end).dot(dir) - tr; + // Tracking tighter than a space's width gives each space a negative advance. + let face_space = space_advance(&self.face) * self.scale; + let space = face_space + tr; + let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 }; + let n = match steps { + Some((joined, apart)) => { + let d = (m.origin - self.matches.last().map_or(self.origin, |p| p.origin)).dot(dir); + // How far `n` spaces set the glyph from where the outlines put it: the pair with one + // space between them is `apart`, and each further space adds a space and the tracking. + let spaced_err = |n: usize| (d - apart + face_space - tr - n as f64 * space).abs(); + // Kerning against a space widens or narrows the gap, so the count the gap gives, the + // counts next to it and the count the measured distance gives are compared; the + // rounded count wins a tie. + let measured = (d - apart + face_space - tr) / space; + let best = [spaces.round(), spaces.floor(), spaces.ceil(), measured.round()] + .into_iter() + .filter(|c| c.is_finite()) + .map(|c| (c.max(1.0) as usize).min(64)) + .min_by(|a, b| spaced_err(*a).total_cmp(&spaced_err(*b))) + .unwrap_or(1); + // The joined pair wins a tie. + if (d - joined - tr).abs() <= spaced_err(best) + self.size() * 1e-5 { 0 } else { best } + } + None if spaces.is_finite() && spaces > 0.5 => (spaces.round() as usize).clamp(1, 64), + None => 0, + }; + self.text.extend(std::iter::repeat_n(' ', n)); self.text.push(m.ch); self.pieces.push(id); self.matches.push(m.clone()); @@ -426,6 +493,15 @@ impl Line { /// its characters, spaces included, from `budget` before it runs; without enough left, the /// line stays as it is, or becomes the best tracked reading laid out before the budget ran out. fn tracked(self, system_layout: bool, budget: &mut usize) -> Line { + let reach = self.text.chars().count(); + self.tracked_reaching(system_layout, budget, reach) + } + + /// [`Line::tracked`] for a line whose tracking is applied to `reach` characters, its glyphs and + /// the spaces between them: a measured tracking within 0.05 of a whole number is read as that + /// number only when the difference moves the character `reach` places on by no more than the + /// tolerance [`first_mismatch`] allows. + fn tracked_reaching(self, system_layout: bool, budget: &mut usize, reach: usize) -> Line { let size = self.size(); let n = self.pieces.len(); // A near-matched glyph sits within the tolerance of where the font draws it, so the gaps @@ -534,7 +610,12 @@ impl Line { let mut tries = vec![]; for seed in [lower, median(extra, true), spaced_seed].into_iter().flatten() { let Some(measured) = measure(seed) else { continue }; - for t in [round_tracking(measured), measured] { + let rounded = round_tracking(measured); + let drift = (rounded - measured).abs() / 1000.0 * size * reach.saturating_sub(1) as f64; + for t in [rounded, measured] { + if t != measured && drift > (size * 0.01).max(0.01) { + continue; + } if !tries.contains(&t) { tries.push(t); } @@ -582,7 +663,12 @@ impl Line { match (tracked.first_mismatch(&tracked.probe(system_layout)), plain_miss) { // Under a unit of tracking, or a word space the tracked reading drops, where // untracked type draws the line: no tracking. - (None, None) if t.abs() < 1.0 || drops_a_word_space => return self, + (None, None) + if (t.abs() < 1.0 && t.abs() / 1000.0 * size * reach.saturating_sub(1) as f64 <= (size * 0.01).max(0.01)) + || drops_a_word_space => + { + return self; + } (None, _) => return tracked, (Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)), _ => {} @@ -688,6 +774,9 @@ fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMat (finite(shape), finite(moved)) } +/// The most glyphs [`verified`] measures the tracking of after a split. +const MEASURE_SPAN: usize = 32; + /// `lines` checked against their own layout: a line splits where its type stops drawing the /// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). /// The glyphs laid out are bounded by a multiple of the number of glyphs. @@ -698,8 +787,8 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) // leave glyphs unchecked; past it they keep no tracking. Each measure takes the glyphs to // rebuild the rest and the characters it lays out (see [`Line::tracked`]); the budget covers // one measure of each whole line, as `retype` gives the first, and the glyph checks' budget. - // The glyphs measured again after splits are limited apart from it, at six times each rest's - // glyphs from half as much again as the glyph checks' budget. + // The glyphs measured again after splits are limited apart from it, at six times the glyphs + // each measure reads from half as much again as the glyph checks' budget. let mut remeasured = budget.saturating_add(budget / 2); let mut track_budget = lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(394))).fold(budget, usize::saturating_add); @@ -744,29 +833,10 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) // The glyphs before the mismatch, then the rest, each checked as a line of its // own: the type before the mismatch may draw otherwise without what follows it (a // font can place a glyph by the glyph after it), and the first glyph on its own - // may still be drawn as it was (a contextual form changed it in the line). The - // rest takes the tracking its own glyphs are spaced by, while the budget for - // measuring it lasts and when type draws its first glyph as it was, followed by the - // next two (else that glyph splits off first, and the tracking is measured from the - // next one); past it, an untracked line's rest keeps its text as it is. + // may still be drawn as it was (a contextual form changed it in the line). Some(k) => { let k = k.max(1); - // A measure takes at least six times the rest's glyphs from each budget. - let measurable = n - k >= 3 && remeasured >= (n - k).saturating_mul(6) && track_budget >= (n - k).saturating_mul(6); - let first_drawn = measurable && { - budget = budget.saturating_sub(3); - l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0)) - }; - let rest = if first_drawn { - // Rebuilding the rest for the measure takes its glyphs from the budget. - remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); - track_budget = track_budget.saturating_sub(n - k); - l.respaced(k, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) - } else if l.tracking == 0.0 { - l.part(k, n) - } else { - l.respaced(k, n, 0.0) - }; + let rest = rest_after_split(&l, k, system_layout, &mut budget, &mut remeasured, &mut track_budget); match rest { Some(r) => todo.push_front(r), None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()), @@ -780,6 +850,75 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) out } +/// The rest of `l` from glyph `k` (at least 1) after [`verified`] splits it there. The rest takes +/// the tracking its own glyphs are spaced by, while the budgets for measuring it last and when type +/// draws its first glyph as it was, followed by the next two (else that glyph splits off first, and +/// the tracking is measured from the next one); past it, an untracked line's rest keeps its text as +/// it is. The tracking is measured from the rest's first [`MEASURE_SPAN`] glyphs at most, and the +/// glyphs after them follow at that tracking, so each split costs the same however long the rest +/// is, and splits at irregular gaps early in a line leave the budget for a long evenly tracked run +/// after them. A gap after the glyphs measured reads as spaces only when they fit it better than +/// the joined pair does, as in the glyphs measured: laying those pairs out is set aside from +/// `track_budget` before the tracking is measured, and without enough for both the rest is not +/// measured. +fn rest_after_split(l: &Line, k: usize, system_layout: bool, budget: &mut usize, remeasured: &mut usize, track_budget: &mut usize) -> Option { + let n = l.pieces.len(); + let span = (n - k).min(MEASURE_SPAN); + let more = n - k - span; + // What [`Line::pair_steps`] takes for the last glyph measured and the glyphs after it. + let pairs = if more > 0 { more.saturating_add(1).saturating_mul(3) } else { 0 }; + // A measure takes at least six times the glyphs it reads from each budget. + let measurable = n - k >= 3 && *remeasured >= span.saturating_mul(6) && *track_budget >= span.saturating_mul(6).saturating_add(pairs); + let first_drawn = measurable && { + *budget = budget.saturating_sub(3); + l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0)) + }; + if !first_drawn { + return if l.tracking == 0.0 { l.part(k, n) } else { l.respaced(k, n, 0.0) }; + } + // Rebuilding the glyphs measured takes them from the budget. + *remeasured = remeasured.saturating_sub(span.saturating_mul(6)); + *track_budget = track_budget.saturating_sub(span).saturating_sub(pairs); + let mut pair_budget = pairs; + // The characters the rest's tracking applies to: its glyphs and the spaces between them (a + // space before glyph `at` follows glyph `at - 1`). + let reach = l + .text + .chars() + .scan(0usize, |glyph, c| { + let at = *glyph; + *glyph += usize::from(c != ' '); + Some(if c == ' ' { at > k } else { at >= k }) + }) + .filter(|kept| *kept) + .count() + .max(n - k); + let mut r = l.respaced(k, k + span, 0.0)?.tracked_reaching(system_layout, track_budget, reach); + // Tracking that leaves a space under half its advance: the gaps alone do not show the spaces + // past the glyphs measured (only the kerning a space breaks may), so the whole rest is measured + // while the budget lasts. + let space = space_advance(&r.face) * r.scale; + if more > 0 + && space + r.tracking_pt() < space / 2.0 + && *remeasured >= (n - k).saturating_mul(6) + && track_budget.saturating_add(pair_budget) >= (n - k).saturating_mul(6) + && let Some(whole) = l.respaced(k, n, 0.0) + { + *remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); + *track_budget = track_budget.saturating_add(pair_budget).saturating_sub(n - k); + return Some(whole.tracked(system_layout, track_budget)); + } + // The glyphs after those measured follow at that tracking. + let steps = match more { + 0 => vec![], + _ => l.matches.get(k + span - 1..).and_then(|ms| r.pair_steps(ms, system_layout, &mut pair_budget)).unwrap_or_default(), + }; + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(k + span).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); + } + Some(r) +} + /// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes /// of the area type on the layers Retype changes /// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 2727dd4432..fd2d74625e 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1385,6 +1385,34 @@ fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() { assert_eq!(r["texts"], json!(["oo"]), "{r}"); } +#[test] +fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_type() { + // An even-odd compound paints the same whichever way its contours run, so an o's counter may + // run the same way as its outer contour: neither the part as it is nor all its contours turned + // is the glyph. Filled by the nonzero rule, the same contours paint the o's counter, and the + // compound stays an outline. + for turned in [1usize, 2] { + let mut s = session(); + let c = one_compound(&mut s, "do"); + // One path per contour: the d's two, then the o's two. + let paths = children_of(&s, c); + assert_eq!(paths.len(), 4, "a d and an o are two contours each"); + let p = paths[paths.len() - turned]; + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(p)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&data.to_bezpath().reverse_subpaths()); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter"); + s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + #[test] fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let mut s = session(); @@ -1707,13 +1735,19 @@ fn slight_tracking_without_spaces_is_kept() { /// The lines Retype reads from the outlines in group `g` (all in the face of its first glyph's /// first match), before their tracking is measured and their layout checked. fn lines_in(s: &Session, g: u64) -> Vec { + lines_in_family(s, g, None) +} + +/// [`lines_in`] with the face of the first glyph's match in `family` when given. +fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec { let d = &s.doc().unwrap().doc; let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces); let db = vectorcraft_text::FontDb::global(); let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted); - let face = index.matches(&pieces[0].path)[0].face.id(); + let first = index.matches(&pieces[0].path); + let face = first.iter().find(|m| family.is_none_or(|f| m.face.family == f)).unwrap_or(&first[0]).face.id(); let mut lines: Vec = vec![]; for pc in &pieces { let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); @@ -1823,6 +1857,286 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() { assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); } +#[test] +fn irregular_gaps_before_a_long_tracked_run_do_not_split_the_run() { + // The first eight gaps each take another tracking, and the 92 glyphs after them are tracked + // 300: measuring the rest after each irregular gap must not use up the budget the run needs, + // so the run is one object with its tracking. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap(); + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + s.execute("text.setRangeStyle", &json!({"id": id, "start": i, "end": i + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "i".repeat(100), "{r}"); + assert_eq!(r["unmatched"], json!([])); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().count(), 92, "{texts:?}"); + assert!(run.runs.iter().all(|r| r.style.tracking == 300.0), "{texts:?}"); +} + +#[test] +fn a_long_run_after_a_split_keeps_the_fraction_of_its_tracking() { + // Tracking 300.04 reads as 300 over the 32 glyphs measured, but 400 glyphs apart the two + // differ by more than the tolerance: the run after the irregular gaps keeps 300.04 and stays + // one object. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(400), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300.04})).unwrap(); + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + s.execute("text.setRangeStyle", &json!({"id": id, "start": i, "end": i + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "i".repeat(400), "{r}"); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().count(), 392, "{texts:?}"); + assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}"); +} + +#[test] +fn a_long_spaced_run_after_a_split_keeps_the_fraction_of_its_tracking() { + // Tracking 300.04 read as 300 moves the last of the 192 glyphs after the irregular gaps by less + // than the tolerance, counting the glyphs alone, but the word spaces between them take the + // tracking too: the run keeps 300.04 and stays one object. + let mut s = session(); + let text = vec!["ii"; 100].join(" "); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300.04})).unwrap(); + // The first eight glyphs, at 0, 1, 3, 4, 6, 7, 9 and 10 (a space after each two). + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + let at = i + i / 2; + s.execute("text.setRangeStyle", &json!({"id": id, "start": at, "end": at + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat().replace(' ', ""), "i".repeat(200), "{r}"); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().filter(|c| *c == 'i').count(), 192, "{texts:?}"); + assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}"); +} + +#[test] +fn a_long_run_after_a_split_keeps_a_tracking_under_one_unit_that_adds_up() { + // Tracking 0.2 moves none of the 32 glyphs measured by more than the tolerance, but moves the + // glyphs 399 places on: the rest after a split keeps it and stays one object. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(400), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 0.2})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert!(near(l.tracking, 0.2, 0.01), "{}", l.tracking); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1); + let last = out.last().unwrap(); + assert!(last.pieces.len() == 399 && near(last.tracking, 0.2, 0.01), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); +} + +#[test] +fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after_a_split() { + // Tracking tighter than the space is wide, by one half to one and a half spaces more, gives the + // space a negative advance; the word space past the glyphs the tracking is measured from is + // still read. + for (unit, times) in + [("AV", 1.5), ("AV", 1.7), ("TA", 1.5), ("TA", 1.7), ("To", 1.5), ("To", 1.7), ("MM", 1.5), ("MM", 1.7), ("Wo", 1.6), ("Wo", 1.8)] + { + let mut s = session(); + let text = format!("{} {}", unit.repeat(20), unit.repeat(5)); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10})).unwrap()["id"].as_u64().unwrap(); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": unit, "size": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in(&s, pg).into_iter().next().unwrap(); + let tracking = -(super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0 * times).round(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking), "{times}"); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1, "{times}"); + let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); + assert_eq!(texts, vec![(&text[1..], tracking)], "{times}"); + } +} + +#[test] +fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_after_a_split() { + // The font adds 120 units to each i before an i. Tracking that leaves a space 120 wide makes the + // gap a kerned pair leaves the same as the gap a word space leaves; the joined reading wins the + // tie, as it does for the glyphs the tracking is measured from. + use vectorcraft_text::test_fonts::{POSITIVE_KERNING_FAMILY, POSITIVE_KERNING_UNITS, positive_kerning_font}; + + vectorcraft_text::FontDb::global().add_font(positive_kerning_font().unwrap()); + let mut s = session(); + let text = "i".repeat(60); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "i", "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in_family(&s, pg, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap(); + let space = super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0; + let tracking = (f64::from(POSITIVE_KERNING_UNITS) - space).round(); + assert!(space + tracking >= space / 2.0, "the space must stay at least half its width: {space} {tracking}"); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in_family(&s, g, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1); + let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); + assert_eq!(texts, vec![(&text[1..], tracking)]); +} + +#[test] +fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_when_the_budget_runs_short() { + // As above, with a measuring budget that covers the tracking's measure but not the layout of + // the pairs after the glyphs measured: those pairs still read no space. + use vectorcraft_text::test_fonts::{POSITIVE_KERNING_FAMILY, POSITIVE_KERNING_UNITS, positive_kerning_font}; + + vectorcraft_text::FontDb::global().add_font(positive_kerning_font().unwrap()); + let mut s = session(); + let text = "i".repeat(60); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "i", "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in_family(&s, pg, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap(); + let space = super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0; + let tracking = (f64::from(POSITIVE_KERNING_UNITS) - space).round(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let l = lines_in_family(&s, g, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); + // What measuring the tracking of the rest's first 32 glyphs takes. + let span = super::MEASURE_SPAN; + let mut measure = 100_000; + let measured = l.respaced(1, 1 + span, 0.0).unwrap().tracked_reaching(false, &mut measure, 59); + assert_eq!(measured.tracking, tracking); + let measure = 100_000 - measure; + // The pairs after the glyphs measured take three characters each. + let pairs = (60 - 1 - span + 1) * 3; + for short in (0..pairs).step_by(7) { + let mut track_budget = (span + measure + short).max(span * 6); + let (mut glyphs, mut remeasured) = (100_000, 100_000); + let r = super::rest_after_split(&l, 1, false, &mut glyphs, &mut remeasured, &mut track_budget).unwrap(); + assert_eq!(r.text, text[1..], "a budget {short} short of the pairs"); + } +} + +#[test] +fn a_word_space_after_a_glyph_kerned_against_it_reads_as_one_space_past_the_glyphs_measured() { + // The font adds 130 units to an i before a space, so the gap before the next glyph is more than + // one and a half spaces wide; the distance the pair with one space between them is laid out at + // fits one space. + use vectorcraft_text::test_fonts::{SPACE_KERNING_FAMILY, space_kerning_font}; + + vectorcraft_text::FontDb::global().add_font(space_kerning_font().unwrap()); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "ii ii", "size": 10, "font": SPACE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let l = lines_in_family(&s, g, Some(SPACE_KERNING_FAMILY)).into_iter().next().unwrap(); + assert_eq!(l.pieces.len(), 4); + let mut r = l.respaced(0, 2, 0.0).unwrap(); + let mut budget = 1_000; + let steps = r.pair_steps(&l.matches[1..], false, &mut budget).unwrap(); + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(2).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); + } + assert_eq!(r.text, "ii ii"); +} + +#[test] +fn a_word_space_after_a_glyph_kerned_toward_it_is_kept_past_the_glyphs_measured() { + // The font takes 130 units off an i before a space, so the gap before the next glyph is under + // half a space wide; the distance the pair with one space between them is laid out at fits it. + use vectorcraft_text::test_fonts::{SPACE_NARROWING_FAMILY, space_narrowing_font}; + + vectorcraft_text::FontDb::global().add_font(space_narrowing_font().unwrap()); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "ii ii", "size": 10, "font": SPACE_NARROWING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let l = lines_in_family(&s, g, Some(SPACE_NARROWING_FAMILY)).into_iter().next().unwrap(); + assert_eq!(l.pieces.len(), 4); + let mut r = l.respaced(0, 2, 0.0).unwrap(); + let mut budget = 1_000; + let steps = r.pair_steps(&l.matches[1..], false, &mut budget).unwrap(); + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(2).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); + } + assert_eq!(r.text, "ii ii"); +} + +#[test] +fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() { + // Tracking as tight as a space is wide leaves the space no advance, and only the kerning it + // breaks shows it is there: the word space past the glyphs the rest's tracking is measured + // from is read by that measure too. + let mut s = session(); + let text = format!("{} {}", "AV".repeat(20), "AV".repeat(5)); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10})).unwrap()["id"].as_u64().unwrap(); + let face = text_of(&s, id).runs[0].style.font_family.clone(); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "AV", "size": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in(&s, pg).into_iter().next().unwrap(); + assert_eq!(pl.face.family, face); + let tracking = -(super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0).round(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1); + let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); + assert_eq!(texts, vec![(&text[1..], tracking)]); +} + #[test] fn tightly_tracked_type_keeps_its_tracking() { // Tracking tighter than a space: the space moves the next glyph back. diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index cf46d853d8..dc33c46ab1 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index e4d89b9c13..341a26a4b1 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1011,6 +1011,154 @@ fn free_in(taken: &mut HashSet, base: &str) -> String { name } +/// [`free_in`] for a library swatch's copy: a numbered name also skips the names `reserved` says +/// the library's other swatches have, so that a later add finds the copy as this swatch's. +fn free_copy_in(taken: &mut HashSet, base: &str, reserved: impl Fn(&str) -> bool) -> String { + let name = if taken.contains(base) { + (2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n) && !reserved(n)).unwrap_or_else(|| base.to_string()) + } else { + base.to_string() + }; + taken.insert(name.clone()); + name +} + +/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered +/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own +/// swatches of those names, so that a color the art brings under a numbered name does not take one +/// of them. While the import runs, a placeholder swatch holds each such name the art does not +/// bring, and a copy of the library's color holds each one the art brings, which the art then +/// takes. The placeholders are removed before it returns, and so is a copy the art did not take; +/// a copy the art took is listed with the colors the import brought. Names of the patterns the +/// import brings are not held. +fn import_holding( + d: &mut vectorcraft_doc::Document, + src: &vectorcraft_doc::Document, + pattern: &str, + names: &HashMap<&str, &Swatch>, +) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> { + let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())); + let taken = taken_names(d); + let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect(); + free.sort_unstable(); + let (mut held, mut copies): (Vec, Vec) = (vec![], vec![]); + if !free.is_empty() { + let brings = patternlib::brought_names(src, pattern); + let patterns = patternlib::brought_patterns(src, pattern); + for n in free.into_iter().filter(|n| !patterns.contains(*n)) { + if !brings.contains(n) { + held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false }); + } else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) { + copies.push((*w).clone()); + } + } + } + let start = d.swatches.len(); + d.swatches.extend(held.iter().chain(&copies).cloned()); + let imported = patternlib::import(d, src, pattern); + let used = |n: &str| { + imported + .as_ref() + .is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n)) + }; + let used: HashSet = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect(); + let mut i = 0; + d.swatches.retain(|w| { + i += 1; + let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint); + !(i > start && ours && !used.contains(&w.name)) + }); + let (target, mut colors, mut took) = imported?; + took.retain(|(from, _)| !used.contains(from)); + colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n))); + Ok((target, colors, took)) +} + +/// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors +/// under the names `links` gives them, for each whose colors `links` names now. Those leave +/// `pending` and are returned. +fn settle<'a>( + d: &mut vectorcraft_doc::Document, + pending: &mut Vec<(String, &'a Swatch)>, + links: &HashMap, +) -> Vec<(String, &'a Swatch)> { + let mut done = vec![]; + pending.retain(|(name, w)| { + let all = all_linked(&w.paint, links); + if all { + done.push((name.clone(), *w)); + } + !all + }); + relink_in(d, &done, links); + done +} + +/// Give the swatches of `d` that `list` names (document name, library swatch) the library swatch's +/// paint with its colors linked to the names `links` gives them, in one pass over the document's +/// swatches. +fn relink_in(d: &mut vectorcraft_doc::Document, list: &[(String, &Swatch)], links: &HashMap) { + if list.is_empty() { + return; + } + let paints: HashMap<&str, Paint> = list.iter().map(|(name, w)| (name.as_str(), relinked(&w.paint, links))).collect(); + for x in d.swatches_iter_mut() { + if let Some(paint) = paints.get(x.name.as_str()) { + x.paint = paint.clone(); + } + } +} + +/// Whether paint `a` shows what paint `b` shows: the same color, or the same gradient with the +/// colors its stops show, whichever swatches those colors link to. +fn shows(a: &Paint, b: &Paint) -> bool { + let unlinked = |p: &Paint| match p { + Paint::Gradient(g) => { + let mut g = g.clone(); + g.swatch = None; + g.gradient.stops.iter_mut().for_each(|s| s.swatch = None); + Paint::Gradient(g) + } + other => other.clone(), + }; + match (a.color(), b.color()) { + (Some(x), Some(y)) => x == y, + _ => unlinked(a) == unlinked(b), + } +} + +/// The names of the swatches the colors of paint `p` link to: a tint's base color, or the colors +/// of a gradient's stops. +fn linked_names(p: &Paint) -> Vec<&str> { + match p { + Paint::Solid { swatch: Some(b), .. } => vec![b.as_str()], + Paint::Gradient(g) => g.gradient.stops.iter().filter_map(|s| s.swatch.as_deref()).collect(), + _ => vec![], + } +} + +/// Paint `p` with each link to a swatch that `links` names changed to the name it maps to. +fn relinked(p: &Paint, links: &HashMap) -> Paint { + let mut out = p.clone(); + let swap = |name: &mut String| { + if let Some(to) = links.get(name.as_str()) { + *name = to.clone(); + } + }; + match &mut out { + Paint::Solid { swatch: Some(b), .. } => swap(b), + Paint::Gradient(g) => g.gradient.stops.iter_mut().filter_map(|s| s.swatch.as_mut()).for_each(swap), + _ => {} + } + out +} + +/// Whether `links` names every swatch the colors of paint `p` link to, the built-in Registration +/// swatch aside (every document has it under its own name). +fn all_linked(p: &Paint, links: &HashMap) -> bool { + linked_names(p).iter().all(|n| *n == REGISTRATION || links.contains_key(*n)) +} + fn add(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.add"; let (info, lib) = library_param(s, p, C)?; @@ -1030,34 +1178,207 @@ fn add(s: &mut Session, p: &Value) -> Result { // The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked // up once so that a large palette takes linear time. let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new(); + // The document's numbered copies ("Ink 2") by the name they are numbered after, in order. + let mut copies: HashMap<&str, Vec<&Swatch>> = HashMap::new(); for w in d.swatches_iter() { - by_name.entry(w.name.as_str()).or_insert(w); + let std::collections::hash_map::Entry::Vacant(e) = by_name.entry(w.name.as_str()) else { continue }; + e.insert(w); + if let Some((base, n)) = w.name.rsplit_once(' ') + && !n.is_empty() + && n.bytes().all(|b| b.is_ascii_digit()) + { + copies.entry(base).or_default().push(w); + } } - let there = |w: &Swatch| match (&w.paint, &patterns) { - (Paint::Pattern { pattern, .. }, Some(src)) => { - patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) - } - _ => match by_name.get(w.name.as_str()) { - Some(x) => x.paint == w.paint, - None => w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == w.paint), - } - .then(|| w.name.clone()), + // The library's swatches by name (the first of a name wins), looked up once. + let mut lib_by_name: HashMap<&str, &Swatch> = HashMap::new(); + for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) { + lib_by_name.entry(w.name.as_str()).or_insert(w); + } + let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect(); + // A color whose name the document gives another color, or a color group, is the numbered copy + // of it that an earlier add or a pattern's art brought in, when that copy is the same color. A + // numbered copy whose name the library gives a swatch of the same paint stands for that swatch + // alone, as adding that swatch finds it under its own name. Paints are compared with their + // colors linked as `links` says ([`relinked`]). + let same_kind = |x: &Swatch, w: &Swatch| x.global == w.global && x.spot == w.spot; + // A color is the same swatch only as the same kind: a library global color is not the + // document's process color of the same name and paint, which a tint cannot link to. + let same_color_kind = |x: &Swatch, w: &Swatch| w.paint.color().is_none() || same_kind(x, w); + let numbered = |w: &Swatch, paint: &Paint, links: &HashMap| { + let c = copies.get(w.name.as_str())?; + let own = |x: &Swatch| lib_by_name.get(x.name.as_str()).is_some_and(|l| relinked(&l.paint, links) == x.paint && same_color_kind(x, l)); + let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w)); + found.map(|x| x.name.clone()) }; + let unlinked = HashMap::new(); + // Whether a library global or spot color that paint `p` links to has no place in `links` + // while the document gives its name another swatch, which such a link would find instead. + let misplaced = |p: &Paint, links: &HashMap| { + linked_names(p) + .into_iter() + .any(|n| !links.contains_key(n) && by_name.contains_key(n) && lib_by_name.get(n).is_some_and(|b| b.global || b.spot)) + }; + let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); + // The picked patterns the document already has, each probed once: library pattern name → its + // name in the document and the colors of the document its art takes under other names. + let mut present: HashMap<&str, Option<(String, patternlib::SwatchNames)>> = HashMap::new(); + if let Some(src) = &patterns { + for (_, w) in &picked { + let Paint::Pattern { pattern, .. } = &w.paint else { continue }; + present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern)); + } + } + // Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors + // linked to swatches of the document → the library's global and spot colors to bring back, + // those this call picks included. + // `x` shows `w`'s paint with each color linked to: the name `links` gives it; its own name when + // that is the document's color of the library color's paint and kind; or, for a library color + // the document has under no name, that color's own name, which then comes in under it. + // Registration and colors the library does not have keep their names. + let fit = |x: &Swatch, w: &Swatch, links: &HashMap| -> Option> { + let (ours, theirs) = (linked_names(&w.paint), linked_names(&x.paint)); + if ours.len() != theirs.len() { + return None; + } + let map: HashMap = ours.iter().zip(&theirs).map(|(l, t)| (l.to_string(), t.to_string())).collect(); + if relinked(&w.paint, &map) != x.paint { + return None; + } + let mut restore = vec![]; + for (&l, &t) in ours.iter().zip(&theirs) { + let ok = match (links.get(l), lib_by_name.get(l).filter(|b| b.global || b.spot)) { + (Some(to), _) => to == t, + (None, None) => l == t, + (None, Some(b)) => match by_name.get(t) { + Some(y) => l == t && y.paint == b.paint && same_kind(y, b), + None if l == t && !group_names.contains(t) => { + restore.push(l.to_string()); + true + } + None => false, + }, + }; + if !ok { + return None; + } + } + Some(restore) + }; + // `paint` is `w`'s paint with the colors it links to as `links` has them in the document → the + // name of the document's swatch, and the library colors to bring back for it ([`fit`]). + let there = |w: &Swatch, paint: &Paint, links: &HashMap| -> Option<(String, Vec)> { + if let (Paint::Pattern { pattern, .. }, Some(_)) = (&w.paint, &patterns) { + let (target, _) = present.get(pattern.as_str())?.as_ref()?; + return library_pattern_swatch(d, w, target).map(|n| (n, vec![])); + } + if let Some(restore) = by_name.get(w.name.as_str()).filter(|x| same_color_kind(x, w)).and_then(|x| fit(x, w, links)) { + return Some((w.name.clone(), restore)); + } + if misplaced(&w.paint, links) { + return None; + } + let found = match by_name.get(w.name.as_str()) { + Some(_) => numbered(w, paint, links), + None if group_names.contains(w.name.as_str()) => numbered(w, paint, links), + None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()), + }; + // A numbered copy brings back the colors it links to that the document deleted, as a + // swatch of `w`'s own name does. + found.map(|n| { + let back = by_name.get(n.as_str()).and_then(|x| fit(x, w, links)).unwrap_or_default(); + (n, back) + }) + }; + // The global or spot color of the document that library color `b` is: its own name, or the + // numbered copy of it that adding `b` would find. While no color or color group has its name, + // a numbered copy is looked for only when this call does not add `b` under its own name. + let base_in_doc = |b: &Swatch| match by_name.get(b.name.as_str()) { + Some(x) if x.paint == b.paint && same_kind(x, b) => Some(b.name.clone()), + Some(_) => numbered(b, &b.paint, &unlinked), + None if group_names.contains(b.name.as_str()) || !picked_names.contains(b.name.as_str()) => numbered(b, &b.paint, &unlinked), + None => None, + }; + // The library's global and spot colors that the picked tints and gradients link to, with the + // name each has in the document: library name → document name. Each is looked up for itself, + // whether or not this call picks it, once. + let mut base_names: HashMap = HashMap::new(); + let mut looked_up: HashSet<&str> = HashSet::new(); + for (_, w) in &picked { + for base in linked_names(&w.paint) { + if !looked_up.insert(base) { + continue; + } + if let Some(n) = lib_by_name.get(base).filter(|b| b.global || b.spot).and_then(|b| base_in_doc(b)) { + base_names.insert(base.to_string(), n); + } + } + } + // A color that the art of a picked pattern the document holds takes under another name (a + // numbered copy that the library also names) is the one the picked tints and gradients link + // to, as when the pattern came in, unless this call adds the color itself. The colors the art + // takes are those of an import into a copy of the document, which adds nothing. + if looked_up.iter().any(|n| !base_names.contains_key(*n)) { + for (_, w) in &picked { + let Paint::Pattern { pattern, .. } = &w.paint else { continue }; + let Some(Some((_, took))) = present.get(pattern.as_str()) else { continue }; + for (from, to) in took.iter().cloned() { + let fits = |b: &&Swatch| by_name.get(to.as_str()).is_some_and(|x| (x.global || x.spot) && x.paint == b.paint && same_kind(x, b)); + if looked_up.contains(from.as_str()) && !picked_names.contains(from.as_str()) && lib_by_name.get(from.as_str()).is_some_and(fits) { + base_names.entry(from).or_insert(to); + } + } + } + } // Library name → the name of the document's swatch. let mut existing: Vec<(String, String)> = vec![]; let mut fresh = vec![]; + // The library colors that the document's tints and gradients found here link to by name while + // the document has no swatch of that name (one deleted without unlinking them): they come back + // under their own names. + let mut restore: Vec = vec![]; + // Those that this call picks: they are added first, so that they keep their names, which the + // art of a pattern added before them could otherwise take. + let mut reserved: HashSet = HashSet::new(); for &(group, w) in &picked { - match there(w) { - Some(name) => existing.push((w.name.clone(), name)), + // A tint or gradient is compared with its colors linked to the names they have here. + let paint = relinked(&w.paint, &base_names); + match there(w, &paint, &base_names) { + Some((name, back)) => { + existing.push((w.name.clone(), name)); + for n in back { + if picked_names.contains(n.as_str()) { + reserved.insert(n); + } else if !restore.contains(&n) { + restore.push(n); + } + } + } None => fresh.push((group, w)), } } + if !reserved.is_empty() { + let (first, rest): (Vec<_>, Vec<_>) = fresh.into_iter().partition(|(_, w)| reserved.contains(&w.name)); + fresh = first; + fresh.extend(rest); + } let undo_before = s.doc()?.history.undo.len(); - // Library name → the name it got in the document. - let added: Vec<(String, String)> = if fresh.is_empty() { + // Library name → the name it got in the document. The colors the patterns brought that no + // library swatch of this call stands for are added too; they are listed after the others and + // are never the one `apply` paints with. + let mut brought_alone: Vec<(String, String)> = vec![]; + // Library name → the name of the document's global or spot color for it, which the tints and + // gradients added here link to: one that is global or spot as the library color is. + let base_of = |l: &str, n: &str| { + let (Some(w), Some(x)) = (lib_by_name.get(l), by_name.get(n)) else { return false }; + (x.global || x.spot) && same_kind(x, w) + }; + let mut links: HashMap = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); + links.extend(base_names); + let added: Vec<(String, String)> = if fresh.is_empty() && restore.is_empty() { vec![] } else { - let (added, reused) = s.edit("Add to Swatches", |d, _| { + let (added, reused, brought) = s.edit("Add to Swatches", |d, _| { let mut out = vec![]; // Library pattern swatches that stand for a swatch added earlier in this call. let mut reused = vec![]; @@ -1069,13 +1390,81 @@ fn add(s: &mut Session, p: &Value) -> Result { // The swatches the patterns imported in this call brought with their art: (library // name, document name). let mut brought: Vec<(String, String)> = vec![]; + // The colors to bring back come first, under their own names, which no swatch or color + // group of the document has; the tints and gradients added here link to them too. + for n in &restore { + let Some(b) = lib_by_name.get(n.as_str()) else { continue }; + let name = free_in(&mut taken, &b.name); + d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() }); + links.insert(n.clone(), name.clone()); + brought.push((n.clone(), name)); + } + // The swatches added here with a link `links` did not name yet: (document name, library + // swatch). + let mut pending: Vec<(String, &Swatch)> = vec![]; for (group, w) in fresh { let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { // The pattern comes with its swatch; a pattern the document has without one // gets one. The swatch a pattern that comes in brings is named after the pattern: // it takes the library swatch's name and color group instead. + // The tints and gradients added so far link to their colors first, so that the + // pattern's art finds them. A color they wait for that the pattern's art brings + // is named by importing the pattern into a copy first. + let brings = if pending.is_empty() { Default::default() } else { patternlib::brought_names(src, pattern) }; + let waited = |n: &&str| !links.contains_key(*n) && brings.contains(*n); + // A global or spot color the pattern brought, or took from the document under + // a numbered name: library name → document name. A color this call picks is + // added under its own name instead of the one the pattern took. A library global + // or spot color is only a document color of its paint and kind, as for `base_of`. + let colors_of = |d: &vectorcraft_doc::Document, colors: &[(String, String)], took: &[(String, String)]| { + let mut out: HashMap = HashMap::new(); + for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { + let library = lib_by_name.get(from.as_str()).filter(|b| b.global || b.spot); + let fits = |x: &Swatch| (x.global || x.spot) && library.is_none_or(|b| x.paint == b.paint && same_kind(x, b)); + if d.swatch(to).is_some_and(fits) { + out.entry(from.clone()).or_insert_with(|| to.clone()); + } + } + out + }; + // The names learned from the copy, which the import into the document confirms. + let mut learned = vec![]; + if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { + let mut probe = d.clone(); + let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?; + for (from, to) in colors_of(&probe, &colors, &took) { + if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) { + e.insert(to); + learned.push(from); + } + } + } + let settled = settle(d, &mut pending, &links); let had = taken_names(d); - let (target, colors) = patternlib::import(d, src, pattern)?; + let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?; + // Those colors are the ones the library's tints of them link to, unless the + // document already has one for them. A name the copy gave that the import + // into the document did not give is replaced, and the tints linked to it are + // linked again. + let mut found = colors_of(d, &colors, &took); + let mut changed = false; + for from in learned { + let real = found.remove(&from); + if real.as_ref() != links.get(&from) { + changed = true; + match real { + Some(to) => links.insert(from, to), + None => links.remove(&from), + }; + } + } + for (from, to) in found { + links.entry(from).or_insert(to); + } + if changed { + relink_in(d, &settled, &links); + pending.extend(settled.into_iter().filter(|(_, w)| !all_linked(&w.paint, &links))); + } brought.extend(colors); if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) { reused.push((w.name.clone(), name)); @@ -1101,8 +1490,29 @@ fn add(s: &mut Session, p: &Value) -> Result { (name.clone(), Swatch { name, paint, global: false, spot: false }) } else { // A color a pattern added earlier in this call brought with its art is that - // swatch: it moves to the library swatch's place. - let at = brought.iter().position(|(from, _)| *from == w.name); + // swatch when it shows the library swatch's color: it moves to the library + // swatch's place, when its colors link where the library swatch's do: to the + // names `links` gives them, not elsewhere for a color this call has yet to add, + // and otherwise to a color of the library color's paint and process, global or spot kind, + // or under the same name when the library has no such swatch (Registration). + let fits = |x: &Paint| { + let (ours, theirs) = (linked_names(&w.paint), linked_names(x)); + ours.len() == theirs.len() + && ours.iter().zip(&theirs).all(|(l, t)| match links.get(*l) { + Some(to) => to == t, + None => { + !picked_names.contains(l) + && match lib_by_name.get(*l) { + Some(b) => d.swatch(t).is_some_and(|x| x.paint == b.paint && same_kind(x, b)), + None => l == t, + } + } + }) + }; + let same = |to: &str| { + d.swatch(to).is_some_and(|x| shows(&x.paint, &w.paint) && x.global == w.global && x.spot == w.spot && fits(&x.paint)) + }; + let at = brought.iter().position(|(from, to)| *from == w.name && same(to)); let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| { let i = d.swatches.iter().position(|x| x.name == n)?; Some(d.swatches.remove(i)) @@ -1110,11 +1520,23 @@ fn add(s: &mut Session, p: &Value) -> Result { match moved { Some(sw) => (sw.name.clone(), sw), None => { - let name = free_in(&mut taken, &w.name); - (name.clone(), Swatch { name, ..(*w).clone() }) + // A numbered copy skips the names of the library's other swatches, + // which a later add looks up as theirs. + let name = free_copy_in(&mut taken, &w.name, |n| lib_by_name.contains_key(n)); + // A tint or gradient links to its colors under the names they have in + // the document; a color that comes in later in this call is linked + // when it has come in. + let paint = relinked(&w.paint, &links); + if !all_linked(&w.paint, &links) { + pending.push((name.clone(), w)); + } + (name.clone(), Swatch { name, paint, ..(*w).clone() }) } } }; + if sw.global || sw.spot { + links.insert(w.name.clone(), name.clone()); + } match group { Some(g) => { let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i); @@ -1135,13 +1557,37 @@ fn add(s: &mut Session, p: &Value) -> Result { } out.push((w.name.clone(), name)); } - Ok((out, reused)) + // A library global or spot color that a tint or gradient added here links to, which the + // document does not have and nothing in this call brought, comes in with it, as pasting + // art painted with the tint brings its color. It is listed with the colors patterns + // brought. + let mut wanted: Vec<&str> = vec![]; + let mut seen: HashSet<&str> = HashSet::new(); + for (_, w) in &pending { + for n in linked_names(&w.paint) { + if n != REGISTRATION && !links.contains_key(n) && seen.insert(n) { + wanted.push(n); + } + } + } + for n in wanted { + let Some(b) = lib_by_name.get(n).filter(|b| b.global || b.spot) else { continue }; + let name = free_copy_in(&mut taken, &b.name, |x| lib_by_name.contains_key(x)); + d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() }); + links.insert(n.to_string(), name.clone()); + brought.push((n.to_string(), name)); + } + relink_in(d, &pending, &links); + Ok((out, reused, brought)) })?; existing.extend(reused); + brought_alone = brought; added }; let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::>(); - let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)}); + let mut added_names = names(&added); + added_names.extend(names(&brought_alone)); + let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)}); if let (Some(cmd), Some((_, first))) = (apply, picked.first()) { let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone()); s.execute(cmd, &json!({"swatch": name, "focus": focus}))?; diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 0d75061bee..3af85a8265 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -11,8 +11,8 @@ use super::menucmds::whole_or; use super::stroke::StrokeChange; use super::typecmd::refresh_bounds; use super::{ - CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index, - number_or, object_param, point_param, str_param, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, finite_numbers, has_doc, has_selection, + index, number_or, object_param, str_param, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Area / Path Type", [], None, - "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", + "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point; anything but two numbers: an error), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", has_doc, create_in_path ), @@ -255,9 +255,15 @@ fn byte_param(p: &Value, k: &str) -> Option { /// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any /// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result { + Ok(offset_given(p, k, cmd)?.unwrap_or(default)) +} + +/// The byte offset that `p` gives for `k`, or `None` when `p` leaves it out or gives null. Any +/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. +fn offset_given(p: &Value, k: &str, cmd: &str) -> Result> { match p.get(k) { - None | Some(Value::Null) => Ok(default), - Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)), + None | Some(Value::Null) => Ok(None), + Some(_) => Ok(Some(index(whole_or(p, k, 0, cmd)?))), } } @@ -280,7 +286,7 @@ pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?), }; - let insert = str_param(p, "insert").unwrap_or("").to_string(); + let insert = text_param(p, "insert", C)?.unwrap_or("").to_string(); let clear = clear_param(s, p, id, C)?; let caret = s.edit("Typing", |d, _| { for other in &clear { @@ -1313,8 +1319,7 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve /// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error /// when there is no character there, it is an inline graphic, or its font is not available. fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range, std::sync::Arc)> { - check_numbers(p, &["start"], c)?; - let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; + let start = offset_given(p, "start", c)?.ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; let mut at = 0; for run in &t.runs { let end = at + run.text.len(); @@ -1558,8 +1563,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result { fn touch_type(s: &mut Session, p: &Value) -> Result { const C: &str = "text.touchType"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; - check_numbers(p, &["start"], C)?; - let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; + let start = offset_given(p, "start", C)?.ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "nothing to change: give dx, dy, hScale, vScale or rotation")); } @@ -1797,7 +1801,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { fn create_in_path(s: &mut Session, p: &Value) -> Result { const C: &str = "text.createInPath"; let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?; - let on_path = match str_param(p, "mode").unwrap_or("area") { + let on_path = match text_param(p, "mode", C)?.unwrap_or("area") { "area" => false, "onPath" | "path" => true, o => return Err(bad(C, format!("mode must be area|onPath, got {o}"))), @@ -1815,8 +1819,12 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { check_switches(p, &["vertical", "placeholder"], C)?; super::color_param(p, "color", C)?; let style = super::create::new_type_style(s, p, C)?; - let text = str_param(p, "text").unwrap_or("").to_string(); - let start = match point_param(p, "at") { + let text = text_param(p, "text", C)?.unwrap_or("").to_string(); + let at = match p.get("at").filter(|v| !v.is_null()) { + None => None, + Some(v) => Some(finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be a point: [x, y]"))?), + }; + let start = match at { Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0), _ => 0.0, }; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 185baf734f..2a62a46374 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -13,7 +13,7 @@ use super::edit::selected_roots; use super::pathops::{length_given, number_given, shape_node}; use super::{ CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or, - object_param, ok, str_param, switch_or, targets, text_param, + object_param, ok, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -873,7 +873,7 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option, mut f: i } fn set_text(s: &mut Session, p: &Value) -> Result { - let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); + let text = text_param(p, "text", "text.setText")?.ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); let ids = text_targets(s, p, "text.setText")?; // The text the type already has is no undo step. edit_if_nodes_changed(s, "Typing", &ids, |d| { diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 498982a7f9..14c5fa6ebd 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -800,11 +800,18 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 transparency: s.transparency, matte, }; - let mut ix = reduced(rgba, w, h, s, &o, &kept)?; + let (mut ix, dropped) = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. let before = ix.palette.clone(); let clear = ix.transparent.map(usize::from); - let mapped: Vec<[u8; 3]> = before.iter().enumerate().filter(|(i, c)| Some(*i) != clear && to_clear.contains(c)).map(|(_, c)| *c).collect(); + let mut mapped: Vec<[u8; 3]> = before.iter().enumerate().filter(|(i, c)| Some(*i) != clear && to_clear.contains(c)).map(|(_, c)| *c).collect(); + // The colors mapped to transparent that did not fit in a fixed palette and whose pixels became + // transparent. + for c in dropped { + if !mapped.contains(&c) { + mapped.push(c); + } + } let remap = web::to_transparent(&mut ix, |i| Some(i) != clear && before.get(i).is_some_and(|c| to_clear.contains(c))); let mut sources = ix.palette.clone(); for (old, new) in remap.iter().enumerate() { @@ -868,8 +875,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 /// color table's fixed one, without the deleted colors. The pixels of a deleted color take the /// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to /// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of -/// `colors` together, and its first opaque colors that fit in the rest. -fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result { +/// `colors` together (the transparent pixels' slot when there are any), and the opaque colors that +/// fit in the rest: the `locked` ones first, in their order, then the others in palette order. Also returns the +/// colors mapped to transparent that did not fit and whose pixels became transparent. +fn reduced( + rgba: &[u8], + w: u32, + h: u32, + s: &WebSettings, + o: &PaletteOptions, + locked: &[[u8; 3]], +) -> std::result::Result<(Indexed, Vec<[u8; 3]>), String> { let table = &s.color_table; let deleted = ColorTable::colors(&table.deleted, "deleted")?; let custom = ColorTable::colors(&table.custom_palette, "customPalette")?; @@ -880,13 +896,13 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc let clear = ix.transparent.map(usize::from); let gone = |i: usize, c: &[u8; 3]| Some(i) != clear && deleted.contains(c); if !ix.palette.iter().enumerate().any(|(i, c)| gone(i, c)) { - return Ok(ix); + return Ok((ix, vec![])); } let left: Vec<[u8; 3]> = ix.palette.iter().enumerate().filter(|&(i, c)| Some(i) != clear && !deleted.contains(c)).map(|(_, c)| *c).collect(); if left.is_empty() || !opaque_left(&left) { return Err(KEEP_ONE.into()); } - return Ok(quantize::quantize_to(rgba, w, h, o, &left)); + return Ok((quantize::quantize_to(rgba, w, h, o, &left), vec![])); } // A fixed palette holds at most `colors` entries, the transparent one included. let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128); @@ -901,32 +917,46 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc return Err(KEEP_ONE.into()); } // The colors mapped to transparent all become the one transparent entry, so together they take - // one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of - // them and no pixel is transparent, that slot goes to the next opaque color instead. - let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true); + // one slot, and the opaque colors fill the rest. With transparent pixels that slot is theirs, so + // the colors mapped to transparent take no entry of their own and their pixels take the + // transparent pixels' entry. Without them, when no pixel takes one of those colors, the slot + // goes to the next opaque color instead. + let kept = fixed_palette(&left, &to_clear, locked, s.colors, has_clear, !has_clear); let mut ix = quantize::quantize_to(rgba, w, h, o, &kept); - clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear); + let dropped = clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear); if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) { - return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false))); + return Ok((quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, locked, s.colors, has_clear, false)), vec![])); } - Ok(ix) + Ok((ix, dropped)) } -/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in -/// `to_clear` are kept and take one slot together; without it they are left out. The list holds -/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry). -fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> { +/// The entries of the fixed palette `left` that fit in `colors`, in palette order. The opaque +/// colors in `locked` are kept first, in the order `locked` lists them (the colors shifted by hand +/// before the locked ones), then the other opaque colors in palette order. With `clear`, +/// the colors in `to_clear` are kept and take one slot together; without it they are left out. The +/// list holds at most 256 entries, less one when `has_clear` (the transparent pixels' entry). +fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], locked: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> { let any_clear = clear && left.iter().any(|c| to_clear.contains(c)); let total = 256 - usize::from(has_clear); - let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear)); - let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room); - let mut clear_room = if clear { total - opaque } else { 0 }; + let room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear)); + let opaque = |c: &&[u8; 3]| !to_clear.contains(c); + let mut first: Vec<[u8; 3]> = vec![]; + for c in locked.iter().filter(opaque).filter(|c| left.contains(c)) { + if first.len() < room && !first.contains(c) { + first.push(*c); + } + } + let rest = room - first.len(); + let others: Vec<[u8; 3]> = left.iter().filter(opaque).filter(|c| !locked.contains(c)).take(rest).copied().collect(); + let mut clear_room = if clear { total - first.len() - others.len() } else { 0 }; left.iter() .copied() .filter(|c| { - let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room }; - let keep = *slots > 0; - *slots = slots.saturating_sub(1); + if !to_clear.contains(c) { + return first.contains(c) || others.contains(c); + } + let keep = clear_room > 0; + clear_room = clear_room.saturating_sub(1); keep }) .collect() @@ -935,32 +965,39 @@ fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: /// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to /// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the /// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later. -fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) { +/// Returns those colors that a pixel took. +fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) -> Vec<[u8; 3]> { let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect(); if dropped.is_empty() { - return; + return vec![]; } let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); - let near = quantize::nearest_entries(rgba, o, &all); - if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) { - return; - } - let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) { - Some(i) => i, - None => { - // A kept color mapped to transparent that no pixel took; at most 255 entries are used then. - let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else { - return; - }; - ix.palette.push(*c); - i + let Indexed { palette, transparent, indices, .. } = ix; + // The entry such pixels take, looked up at the first of them. + let mut entry: Option> = None; + let mut taken = vec![false; dropped.len()]; + let mut pixel = 0; + quantize::nearest_entries(rgba, o, &all, |n| { + if let Some(d) = n.and_then(|n| n.checked_sub(kept.len())) { + let e = *entry.get_or_insert_with(|| { + transparent.or_else(|| palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())).or_else(|| { + // A kept color mapped to transparent that no pixel took; at most 255 entries are used then. + let c = kept.iter().find(|c| to_clear.contains(c))?; + let i = u8::try_from(palette.len()).ok()?; + palette.push(*c); + Some(i) + }) + }); + if let (Some(e), Some(v)) = (e, indices.get_mut(pixel)) { + *v = e; + if let Some(t) = taken.get_mut(d) { + *t = true; + } + } } - }; - for (v, n) in ix.indices.iter_mut().zip(&near) { - if n.is_some_and(|n| n >= kept.len()) { - *v = entry; - } - } + pixel += 1; + }); + dropped.into_iter().zip(taken).filter(|(_, t)| *t).map(|(c, _)| c).collect() } /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index ba8f7e94ab..006f39ac19 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), @@ -529,9 +529,15 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { Some(v) => { let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`stop` must be a stop index"))?; let color = super::paint::new_color(s, p, color_value(c).ok_or_else(|| bad(C, format!("bad color {c}")))?); - let (fill, stroke_paint) = s.proxy_paints(); - let Paint::Gradient(g) = (if stroke { stroke_paint } else { fill }) else { - return Err(bad(C, "the paint behind the proxy is not a gradient")); + let (paint, source) = match given_stop_paint(s, p, stroke)? { + Some(paint) => (paint, "the paint of the first object in `ids`"), + None => { + let (fill, stroke_paint) = s.proxy_paints(); + (if stroke { stroke_paint } else { fill }, "the paint behind the proxy") + } + }; + let Paint::Gradient(g) = paint else { + return Err(bad(C, format!("{source} is not a gradient"))); }; let mut stops = g.gradient.stops; let n = stops.len(); @@ -550,6 +556,24 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { Ok(result) } +/// The paint whose gradient `paint.sampleColor` recolors a stop of when `p` gives `stop` and +/// objects in `ids`: the fill (or stroke, `stroke`) of the first object `paint.editGradient` edits +/// for those ids (a compound path for its member, a group's painted objects, not the art of a graph +/// design in a series). None without `stop` or without objects in `ids`: the gradient behind the +/// proxy is used. +fn given_stop_paint(s: &Session, p: &Value, stroke: bool) -> Result> { + const C: &str = "paint.sampleColor"; + if p.get("stop").is_none_or(Value::is_null) || p.get("ids").and_then(Value::as_array).is_none_or(Vec::is_empty) { + return Ok(None); + } + let q = json!({ "ids": p.get("ids"), "stroke": stroke }); + let item = super::appearance::item_target(s, &q, C)?.of_kind(s, !stroke); + let ids = super::appearance::drop_design_art_rows(s, item.targets_for(s, &q, !stroke)?, item, !stroke, C)?; + let d = &s.doc()?.doc; + let Some(n) = ids.first().and_then(|id| d.node(*id)) else { return Ok(None) }; + Ok(Some(super::paint::proxy_paint(n, stroke, None))) +} + // ---------- artboards ---------- fn artboard_move(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..abc7fa0740 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -782,15 +782,17 @@ impl ScriptScope { self.allows(&real.join(rest)) } - /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. + /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. Whether + /// it is hidden is a link's own, and the rest is what the link leads to. pub(crate) fn stat(&self, path: &Path) -> Result { let real = self.locate(path)?; let meta = std::fs::metadata(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; - let link = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()); + let own = std::fs::symlink_metadata(path).ok().filter(|m| m.file_type().is_symlink()); + let link = own.is_some(); #[cfg(windows)] - let hidden = std::os::windows::fs::MetadataExt::file_attributes(&meta) & 2 != 0; + let hidden = std::os::windows::fs::MetadataExt::file_attributes(own.as_ref().unwrap_or(&meta)) & 2 != 0; #[cfg(not(windows))] - let hidden = real.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')); + let hidden = if link { path.file_name() } else { real.file_name() }.is_some_and(|n| n.to_string_lossy().starts_with('.')); Ok(ScriptEntry { dir: meta.is_dir(), file: meta.is_file(), diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 99a2569005..06cc86859e 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -55,6 +55,8 @@ pub(crate) struct PreviewCopies { pub(crate) from: Arc, /// The transform or perspective edit copied these objects. pub(crate) roots: Vec, + /// Each copy is directly below its original, not above it. + pub(crate) below: bool, /// This is `from` with the copies added, untransformed. pub(crate) doc: Arc, /// This is the selection after copying, with the copies selected. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..68067dc697 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -75,8 +75,9 @@ pub struct Session { /// back as it was at the release ([`Session::pointer`]). pub(crate) lender: Option>, /// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the - /// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the - /// colors the bucket paints with ([`Session::bucket_paints`]). + /// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent + /// is deactivated as it goes back: their paint commands change the colors the bucket paints + /// with ([`Session::bucket_paints`]). pub(crate) back_to_bucket: bool, /// Pointer and key input that came while the tool computed an edit on another thread, each with /// its number and view, made in order once the edit is applied. diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index c0694bbd81..94ef3bdf9e 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -67,8 +67,15 @@ //! file and once more for each such object. `write` joins its values only for an open file and //! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the //! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed. -//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`. -//! `execute` is counted in the report's `fileExecutes`. +//! - On Unix, where a name that starts with a dot is hidden, setting `hidden` renames the file in +//! its folder, adding one dot or taking its leading dots off, under the rules for `rename`: the +//! old and the new name must both be places the script may write, and a name in use is refused. +//! `createAlias` makes a symbolic link at the object's path, a place the script may write where +//! nothing is, that leads to the real path of a file the script may read. `hidden` and `alias` +//! tell of a link itself, and setting `hidden`, `rename` and `remove` change the link, never what +//! it leads to. On other systems both set `error` and change nothing. +//! - `execute` is not available: it returns `false`, sets `error`, and is counted in the report's +//! `fileExecutes`. //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; @@ -118,6 +125,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; +#[cfg(not(unix))] pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases"; pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed"; pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed"; @@ -1883,44 +1891,41 @@ fn remove(host: &Host, a: &[Data]) -> Result { /// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path. fn rename(host: &Host, a: &[Data]) -> Result { let (path, name) = (arg_text(a, 0), arg_text(a, 1)); + let mut disk = host.disk.borrow_mut(); + Ok(match rename_in(&mut disk, &path, &name) { + Ok(new) => Data::Object(vec![("fs".into(), Data::String(new))]), + Err(m) => error(m), + }) +} + +/// Renames the file or folder at `path`, a link itself, to `name` in the same folder. → its new +/// path. +fn rename_in(disk: &mut Disk, path: &str, name: &str) -> Result { let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':'))); if bad || name.contains('\0') { - return Ok(error(BAD_NAME)); + return Err(BAD_NAME); } - let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) }; - let mut disk = host.disk.borrow_mut(); - let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) { - (Ok(f), Ok(t)) => (f, t), - (Err(m), _) | (_, Err(m)) => return Ok(error(m)), - }; - let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) }; + let new = Path::new(path).parent().map(|p| p.join(name).to_string_lossy().into_owned()).ok_or(ACCESS_DENIED)?; + let (from, to) = (disk.target(path, false)?, disk.target(&new, false)?); + let was = std::fs::symlink_metadata(&from).map_err(|_| NOT_FOUND)?; // A folder that holds the settings folder is not moved, also when its name is given in another // case where case does not matter. let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept)); if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) { - return Ok(error(ACCESS_DENIED)); + return Err(ACCESS_DENIED); } // A name that differs in case alone may name the same file, which then takes the new name. if let Ok(there) = std::fs::symlink_metadata(&to) && !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there))) { - return Ok(error(NAME_TAKEN)); + return Err(NAME_TAKEN); } // Open objects hold real paths with the names the file system keeps, and `from` keeps the last // name as given, which where case does not matter can differ in case: they are matched by the // kept name. A link is renamed itself, and no object holds a path through it. When the kept // name cannot be learned, nothing is renamed, so no object goes on under the old path's rules. - let kept = if was.file_type().is_symlink() { - from.clone() - } else { - match std::fs::canonicalize(&from) { - Ok(kept) => kept, - Err(_) => return Ok(error(WRITE_FAILED)), - } - }; - if std::fs::rename(&from, &to).is_err() { - return Ok(error(WRITE_FAILED)); - } + let kept = if was.file_type().is_symlink() { from.clone() } else { std::fs::canonicalize(&from).map_err(|_| WRITE_FAILED)? }; + std::fs::rename(&from, &to).map_err(|_| WRITE_FAILED)?; // Open objects of the file, or of files in the folder, write to the new path, and the rules for // reading apply to them there. let moved = |p: &mut Option| { @@ -1935,7 +1940,102 @@ fn rename(host: &Host, a: &[Data]) -> Result { // The old path no longer holds the file, so the report names it as well as the new one. disk.wrote(&from); disk.wrote(&to); - Ok(Data::Object(vec![("fs".into(), Data::String(new))])) + Ok(new) +} + +/// `setHidden(path, hidden)`: on Unix, where a name that starts with a dot is hidden, the file or +/// link at `path` (a link itself, never what it leads to) renamed with one dot added or its leading +/// dots taken off; → `{fs}`, its path. A file already as asked keeps its name. A name that would be +/// left empty, a folder, and every system that is not Unix give `{error}`. +fn set_hidden(host: &Host, a: &[Data]) -> Result { + let (path, on) = (arg_text(a, 0), matches!(a.get(1), Some(Data::Bool(true)))); + let mut disk = host.disk.borrow_mut(); + let at = match disk.target(&path, false) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + if !cfg!(unix) { + return Ok(error(NO_HIDDEN)); + } + match std::fs::symlink_metadata(&at) { + Err(_) => return Ok(error(NOT_FOUND)), + Ok(m) if m.is_dir() => return Ok(error(NOT_REGULAR)), + Ok(_) => {} + } + let Some(name) = Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) }; + if name.starts_with('.') == on { + return Ok(Data::Object(vec![("fs".into(), Data::String(path))])); + } + let new = if on { format!(".{name}") } else { name.trim_start_matches('.').to_string() }; + if new.is_empty() { + return Ok(error(NO_HIDDEN)); + } + Ok(match rename_in(&mut disk, &path, &new) { + Ok(fs) => Data::Object(vec![("fs".into(), Data::String(fs))]), + Err(m) => error(m), + }) +} + +/// `createAlias(path, target)`: on Unix a symbolic link at `path` that leads to the real path of the +/// file `target`. `path` must be a place the script may write where nothing is, not even a link +/// that leads nowhere, and `target` a file the script may read. Every system that is not Unix gives +/// `{error}`. +fn create_alias(host: &Host, a: &[Data]) -> Result { + let (path, to) = (arg_text(a, 0), arg_text(a, 1)); + let mut disk = host.disk.borrow_mut(); + let at = match disk.target(&path, false) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + if std::fs::symlink_metadata(&at).is_ok() { + return Ok(error(NAME_TAKEN)); + } + if to.is_empty() { + return Ok(error(NOT_FOUND)); + } + let real = match disk.stat(&to) { + Ok(Some(e)) if e.file => disk.checked(&to).ok().and_then(|p| disk.scope.locate(p).ok()), + Ok(Some(_)) => return Ok(error(NOT_REGULAR)), + Ok(None) => return Ok(error(NOT_FOUND)), + Err(m) => return Ok(error(m)), + }; + let Some(real) = real else { return Ok(error(ACCESS_DENIED)) }; + #[cfg(test)] + if let Some(hook) = BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take()) { + hook(&at); + } + Ok(make_link(&mut disk, &at, &real)) +} + +/// A symbolic link at the real path `at` that leads to the real path `real`. → `true`, or `{error}`. +#[cfg(unix)] +fn make_link(disk: &mut Disk, at: &Path, real: &Path) -> Data { + // Making the link fails when something took its place since it was looked up. + if std::os::unix::fs::symlink(real, at).is_err() { + return error(WRITE_FAILED); + } + // A link put in place of a folder above it since it was looked up may have taken the new link + // elsewhere: that link is removed again, when it is still the one made here. + let placed = at.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c == p)); + let ours = std::fs::read_link(at).is_ok_and(|l| l == real); + if !placed { + if ours { + let _ = std::fs::remove_file(at); + } + return error(ACCESS_DENIED); + } + // Something else at `at` replaced the new link since it was made: it is left alone. + if !ours { + return error(WRITE_FAILED); + } + disk.wrote(at); + Data::Bool(true) +} + +/// Every system that is not Unix: `{error}` with [`NO_ALIAS`]. +#[cfg(not(unix))] +fn make_link(_: &mut Disk, _: &Path, _: &Path) -> Data { + error(NO_ALIAS) } /// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on @@ -2309,13 +2409,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr })) }; let value = |s: &str| HostItem::Value(Data::String(s.to_string())); - let text = HostItem::Object(vec![ - ("notOpen".into(), value(NOT_OPEN)), - ("badMode".into(), value(BAD_MODE)), - ("noAlias".into(), value(NO_ALIAS)), - ("noHidden".into(), value(NO_HIDDEN)), - ("tooLarge".into(), value(TOO_LARGE)), - ]); + let text = + HostItem::Object(vec![("notOpen".into(), value(NOT_OPEN)), ("badMode".into(), value(BAD_MODE)), ("tooLarge".into(), value(TOO_LARGE))]); let system = if WINDOWS { "Windows" } else if cfg!(target_os = "macos") { @@ -2357,6 +2452,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("create".into(), call(link, create)), ("setLength".into(), call(link, set_length)), ("setReadonly".into(), call(link, set_readonly)), + ("setHidden".into(), call(link, set_hidden)), + ("createAlias".into(), call(link, create_alias)), ("pick".into(), call(link, pick)), ]; realm.define_file_classes(items) @@ -2367,9 +2464,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr #[cfg(test)] pub(crate) type CopyHook = Box; +/// Tests: what the next `createAlias` does with the real path of its link. +#[cfg(test)] +pub(crate) type AliasHook = Box; + #[cfg(test)] thread_local! { pub(crate) static BEFORE_COPY_READ: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Tests: what the next `createAlias` does with the real path of its link, after looking it up + /// and before making the link. + pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; /// Tests: while set, the bytes `flush` writes fail after the file was opened for them. pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..1685adc40f 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,10 @@ impl Session { }); // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); + // Direct Selection picks and outlines the parts of a dynamic symbol's instance where the + // effects of the instance's fill and stroke draw them. + vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts); + vectorcraft_doc::hit::set_instance_reshapes(vectorcraft_render::effects::has_item_geometry); // Clicks inside a clip group fall in the region its clipping path's effects give it. vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); // Clicks and marquees find paths, compound paths, groups and layers where their geometry diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index bbd20fa5bb..e2ba1715b9 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -433,11 +433,12 @@ impl Session { let m = cmd::matrix_param(&preview.1, "matrix"); if let Some(m) = m { // The options are the last preview's params with the values it noted, without the - // matrix and the ids. + // matrix, the ids and `drawBehind` (Transform Again puts its copies above). let mut options = preview.1.clone(); if let Some(o) = options.as_object_mut() { o.remove("matrix"); o.remove("ids"); + o.remove("drawBehind"); } st.last_transform = Some(LastTransform::Matrix(m, options)); st.last_perspective = None; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d92bcb7d71..e524d1c63c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3492,6 +3492,65 @@ fn flare_counts_are_whole_numbers() { assert!(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 2.5})).is_err()); } +/// `shape.flare` given only one of `x2` and `y2`, the other left out or null, refuses the call +/// naming the missing one, draws nothing and adds no undo step. +#[test] +fn flare_requires_both_endpoint_coordinates() { + let mut s = session(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.node_count(), st.history.undo.len(), st.history.redo.len()) + }; + let before = state(&s); + for (p, key) in [ + (json!({"cx": 100, "cy": 100, "x2": 300}), "y2"), + (json!({"cx": 100, "cy": 100, "x2": 300, "y2": null}), "y2"), + (json!({"cx": 100, "cy": 100, "y2": 300}), "x2"), + (json!({"cx": 100, "cy": 100, "x2": null, "y2": 300}), "x2"), + ] { + let err = s.execute("shape.flare", &p).expect_err(&p.to_string()).to_string(); + assert_eq!(err, format!("invalid parameters for `shape.flare`: missing number `{key}`"), "{p}"); + assert_eq!(state(&s), before, "{p}"); + } +} + +/// `shape.flare` with neither `x2` nor `y2` (left out or null) places the rings' end point from +/// `pathLength` and `direction`; with both it uses them. +#[test] +fn flare_omitted_or_null_endpoint_coordinates_use_path_fallback() { + let mut s = session(); + let mut end = |p: serde_json::Value| { + let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap()); + let spec = flare_settings(&s.doc().unwrap().doc, id).expect("a flare"); + Point::new(spec.params["x2"].as_f64().unwrap(), spec.params["y2"].as_f64().unwrap()) + }; + for p in [ + json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0}), + json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": null}), + json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "y2": null}), + json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": null, "y2": null}), + ] { + let e = end(p.clone()); + assert!((e.x - 300.0).abs() < 1e-9 && (e.y - 100.0).abs() < 1e-9, "{p}: {e:?}"); + } + assert_eq!(end(json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": 40, "y2": 70})), Point::new(40.0, 70.0)); +} + +/// Settings a file holds with only one of `x2` and `y2` are not a flare's: the group stays as art, +/// but is not a flare that can be edited. +#[test] +fn flare_settings_with_a_lone_endpoint_coordinate_are_not_a_flare() { + let mut s = session(); + let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + let mut d = (*s.doc().unwrap().doc).clone(); + assert!(flare_settings(&d, id).is_some()); + let mut extras = d.node_mut(id).unwrap().extras_mut(); + let spec = extras.flare.as_deref_mut().expect("flare settings"); + spec.params.as_object_mut().unwrap().remove("y2"); + drop(extras); + assert!(flare_settings(&d, id).is_none()); +} + /// `shape.editFlare` on a flare scaled far down: a `pathLength`, an end point or a center that, /// taken back to where the flare was drawn, is not a finite number is an error, and the flare keeps /// its settings. diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index a04bb89b4a..9a29f9e026 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -1129,6 +1129,30 @@ fn shared_effects_and_new_fills_reach_every_selected_object() { assert!(s.execute("appearance.moveItem", &json!({"from": 1, "to": 0, "aligned": true})).is_err()); } +/// Aligned rows copied to `to`: refused when the selected stacks differ, and placed at `to` in each object when the +/// stacks are the same, as an aligned move is. +#[test] +fn aligned_copies_go_to_to_when_the_stacks_are_the_same() { + let mut s = session(); + let (a, b) = mixed_circles(&mut s, true); + let was = (node(&s, a).appearance.clone(), node(&s, b).appearance.clone()); + assert!(s.execute("appearance.duplicateItem", &json!({"index": 1, "to": 0, "aligned": true})).is_err()); + assert_eq!((node(&s, a).appearance.clone(), node(&s, b).appearance.clone()), was, "nothing changed"); + + let mut s = session(); + let (a, b) = mixed_circles(&mut s, false); + run(&mut s, "paint.setFill", json!({"ids": [b.0], "color": "#ffff00"})); + assert_eq!(node(&s, a).appearance, node(&s, b).appearance); + let steps = s.doc().unwrap().history.undo.len(); + // The stroke (row 1) copied to the bottom of each stack: [Stroke, Fill, Stroke]. + run(&mut s, "appearance.duplicateItem", json!({"index": 1, "to": 0, "aligned": true})); + for id in [a, b] { + assert_eq!(node(&s, id).appearance.items.iter().map(AppearanceItem::kind_name).collect::>(), ["stroke", "fill", "stroke"]); + assert_eq!(stroke(&node(&s, id), 0).width, 11.0); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); +} + /// An effect applied to the first object's stroke row goes on the equal stroke of the other /// object, which sits lower in a longer stack there. #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index b37550d5c5..32a9db4b21 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3493,6 +3493,34 @@ fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_clic assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample"); } +/// A Cmd-drag of a corner widget with the Live Paint Bucket that is cut short by choosing the +/// bucket again (the Selection tool it lent cancels the drag as it goes back) leaves the bucket's +/// colors as they were, with New Art Has Basic Appearance off: the selected object's appearance +/// does not replace them. +#[test] +fn live_paint_bucket_keeps_its_colors_when_a_lent_drag_is_cut_short() { + let v = ViewInfo::default(); + let mut s = session(); + let rect = rect(&mut s, 300.0, 300.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap(); + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.select_tool("livePaintBucket", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let fill = s.paint.fill.clone(); + let st = s.doc().unwrap(); + let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let cmd = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 8.0, at.y + 8.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection", "the bucket lent the Selection tool for the drag"); + assert!(s.in_interaction(), "the corner widget drag is in progress"); + s.select_tool("livePaintBucket", v).unwrap(); + assert_eq!(s.tool_id(), "livePaintBucket"); + assert_eq!(s.paint.fill, fill, "the bucket's fill stays"); +} + /// A gradient stop selected on the selection's gradient is not selected once the Live Paint /// Bucket is active (its proxies show the default paint), and one selected on the bucket's /// gradient is not selected once another tool is chosen. diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index e862a03aaf..028ffa6487 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -176,6 +176,13 @@ fn click(s: &mut Session, mods: Mods, x: f64, y: f64) { } } +/// The path the last `shape.curvatureCircle` drew on. +fn drawn_on(s: &Session) -> NodeId { + let (cmd, p) = s.journal.last().unwrap().clone(); + assert_eq!(cmd, C); + id_of(&p) +} + /// With the Curvature Circle tool, a click on a path draws the circle that matches it there, in /// one undo step; with Shift, on the other side. A click on a straight line or away from every /// path draws nothing. @@ -223,4 +230,27 @@ fn the_next_click_passes_over_the_circle_the_tool_drew() { assert_eq!(object_count(&s), count + 1, "the circle drawn first is within reach again"); let third = *s.doc().unwrap().selection.objects.first().unwrap(); assert!(bounds_are(&s, third, Rect::new(100.0, 200.0, 300.0, 400.0)), "the click drew the first circle's own circle"); + assert_eq!(drawn_on(&s), first, "the click hit the first circle"); +} + +/// After Deselect, the pointer reaches the circle the tool drew again, with no edit in between, +/// and still does when the circle is selected again before the pointer moves. +#[test] +fn after_deselect_the_pointer_reaches_the_circle_the_tool_drew() { + for reselect in [false, true] { + let mut s = session(); + let path = parabola(&mut s); + s.select_tool("curvatureCircle", view()).unwrap(); + click(&mut s, Mods::default(), 200.0, 200.0); + let first = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_eq!(drawn_on(&s), path); + let undo = undo_len(&s); + s.execute("select.none", &json!({})).unwrap(); + if reselect { + s.execute("select.set", &json!({"ids": [first.0]})).unwrap(); + } + assert_eq!(undo_len(&s), undo, "Deselect is not an edit"); + click(&mut s, Mods::default(), 280.0, 236.0); + assert_eq!(drawn_on(&s), first, "the click hit the circle drawn first ({reselect})"); + } } diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..f8c6182a53 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2692,6 +2692,28 @@ fn a_smooth_drag_that_only_meets_corners_adds_no_undo_step() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +/// Drags of the Smooth tool again and again along the lower half of an ellipse add no anchors after +/// the first, which splits the two segments the drag's reach ends on, and leave no corner. The +/// anchors at those splits lie on the edge of the next drag's reach, where the segment beyond each +/// one is in reach at that anchor only, so the next drag leaves that segment as it is. +#[test] +fn smooth_drags_again_and_again_along_part_of_an_ellipse_add_no_anchors_or_corners() { + let mut s = session(); + let r = s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let drag: Vec = + (0..=32).map(|i| f64::from(i) / 32.0 * std::f64::consts::PI).map(|a| Point::new(200.0 + 100.0 * a.cos(), 160.0 + 60.0 * a.sin())).collect(); + let mut first = None; + for pass in 1..=6 { + smooth_pass(&mut s, &drag); + let p = path(&s, id); + let turns = smooth_anchor_turns(&p.subpaths[0]); + assert!(turns.iter().all(|t| *t < 1.0), "pass {pass} leaves a corner: {turns:?}"); + assert_eq!(p.anchor_count(), *first.get_or_insert(p.anchor_count()), "pass {pass}"); + } +} + #[test] fn join_tool_joins_two_lines() { let mut s = session(); @@ -3313,6 +3335,66 @@ fn path_eraser_width_outside_its_range_is_refused() { } } +/// `path.smoothRegion` refuses a `radius` outside 0.001 to 1000 pt and a `fidelity` outside the +/// Smooth tool's tolerance range, and `path.joinScrub` a `tolerance` outside 0.001 to 1000 pt: the +/// document, the selection and the undo history do not change. The ends of each range are taken, +/// and null is read as the key left out, which smooths or joins in one undo step. +#[test] +fn smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range() { + let mut s = session(); + let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": if i % 2 == 0 { 200.0 } else { 203.0 }})).collect(); + let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let drag = json!({"points": [[90, 200], [200, 200], [310, 200]]}); + let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + let reaches = [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)]; + let fidelities = [json!(0), json!(-1), json!(lo / 2.0), json!(hi * 1.01), json!(1e300)]; + let refused = reaches + .iter() + .map(|x| ("radius", x, "`radius` must be from 0.001 to 1000".to_string())) + .chain(fidelities.iter().map(|x| ("fidelity", x, format!("`fidelity` must be from {lo} to {hi} pt")))); + for (key, x, want) in refused { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({ key: x })), &want); + assert_eq!(s.doc().unwrap().selection, sel, "{key} {x} changed the selection"); + } + for extra in [json!({"radius": 0.001}), json!({"radius": 1000}), json!({"fidelity": lo}), json!({"fidelity": hi})] { + let undo = undo_steps(&s); + s.execute("path.smoothRegion", &with(&drag, extra.clone())).unwrap_or_else(|e| panic!("{extra}: {e}")); + while undo_steps(&s) > undo { + s.execute("edit.undo", &json!({})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + } + let before = path(&s, id); + let undo = undo_steps(&s); + s.execute("path.smoothRegion", &with(&drag, json!({"radius": null, "fidelity": null}))).unwrap(); + assert!(path(&s, id) != before, "the default radius and fidelity smoothed nothing"); + assert_eq!(undo_steps(&s), undo + 1); + + let mut s = session(); + line(&mut s, 100.0, 100.0, 200.0, 100.0); + line(&mut s, 205.0, 100.0, 300.0, 150.0); + s.execute("select.none", &json!({})).unwrap(); + let scrub = json!({"points": [[202, 90], [202, 110]]}); + for x in &reaches { + refuses_with(&mut s, "path.joinScrub", &with(&scrub, json!({"tolerance": x})), "`tolerance` must be from 0.001 to 1000"); + assert_eq!(paths(&s).len(), 2, "tolerance {x}"); + } + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 0.001}))).unwrap(); + assert_eq!(paths(&s).len(), 2, "0.001 pt reaches neither end"); + let undo = undo_steps(&s); + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 1000}))).unwrap(); + while undo_steps(&s) > undo { + s.execute("edit.undo", &json!({})).unwrap(); + } + s.execute("select.none", &json!({})).unwrap(); + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": null}))).unwrap(); + assert_eq!(paths(&s).len(), 1, "the default tolerance joined nothing"); + assert_eq!(undo_steps(&s), undo + 1); +} + /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, /// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index e136d9f45b..fc1305a0a7 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -587,6 +587,186 @@ fn direct_selection_paints_one_object_of_one_dynamic_instance() { assert_eq!(pixel(&s, 80, 30), BLUE); } +/// Instance `inst` with a new fill (`fill`) or stroke row without paint whose effect is `effect` +/// with `params`. +fn row_effect(s: &mut Session, inst: NodeId, fill: bool, effect: &str, params: Value) { + s.execute(if fill { "appearance.addFill" } else { "appearance.addStroke" }, &json!({"ids": [inst.0]})).unwrap(); + let row = node(s, inst).appearance.items.len() - 1; + s.execute("appearance.setItem", &json!({"ids": [inst.0], "index": row, "none": true})).unwrap(); + s.execute("effect.apply", &json!({"ids": [inst.0], "item": row, "effect": effect, "params": params})).unwrap(); +} + +/// The object of `inst`'s art that Direct Selection picks at (`x`, `y`) with `opt`. +fn part_at(s: &Session, inst: NodeId, (x, y): (f64, f64), opt: vectorcraft_doc::hit::HitOptions) -> Option> { + let doc = &s.doc().unwrap().doc; + vectorcraft_doc::hit::symbol_part_at(doc, doc.node(inst).unwrap(), vectorcraft_geom::Point::new(x, y), opt) +} + +/// The box of the outline of the object at `path` in `inst`'s art, as Direct Selection draws it. +fn part_outline_box(s: &Session, inst: NodeId, path: &[u32]) -> Rect { + use vectorcraft_geom::kurbo::Shape; + let doc = &s.doc().unwrap().doc; + let outline = vectorcraft_doc::hit::symbol_part_outline_in_view(doc, doc.node(inst).unwrap(), path, Default::default()).unwrap(); + outline.bounding_box() +} + +/// A geometry effect on a dynamic instance's fill or stroke moves where the objects of its art +/// are drawn: Direct Selection picks an object where it is drawn, not where its own shape no longer +/// paints, and outlines it there; Outline view still takes the plain shapes. +#[test] +fn direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The squares are drawn at x 110..150 and 160..200. + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the first square where it is drawn"); + assert_eq!(part_at(&s, inst, (180.0, 30.0), opt), Some(vec![1]), "the second square where it is drawn"); + assert_eq!(part_at(&s, inst, (80.0, 30.0), opt), None, "where the second square's own shape no longer paints"); + assert_eq!(part_at(&s, inst, (60.5, 30.0), opt), None, "the plain edge of the second square"); + assert_eq!(part_at(&s, inst, (60.5, 30.0), HitOptions { outline: true, ..opt }), Some(vec![1]), "Outline view draws the plain shapes"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 110.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline follows the moved square: {b:?}"); + direct(&mut s, (130.0, 30.0), (130.0, 30.0), Mods::default()); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.objects, [inst]); + assert_eq!(sel.symbol_part, Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![0] }), "a press on the drawn square picks it"); + + // A stroke effect: Offset Path moves the first square's stroke out to x = 0. + let mut s = session(); + let (a, b) = (square(&mut s, 10.0), square(&mut s, 60.0)); + s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#00ff00"})).unwrap(); + let inst = id(&s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, false, "path.offsetPath", json!({"offset": 10})); + assert_eq!(part_at(&s, inst, (0.5, 30.0), opt), Some(vec![0]), "the moved stroke"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), Some(vec![0]), "the fill keeps its shape"); + let b = part_outline_box(&s, inst, &[0]); + assert!(b.x0 < 1.0 && b.x1 > 59.0, "the outline takes in the moved stroke: {b:?}"); + + // A symbol instance in the art takes the effect too: it is picked and outlined where its art is + // drawn, not in its box. The fill effect moves its square; its image has no fill and stays. + let mut s = session(); + let a = square(&mut s, 10.0); + place_image(&mut s); + let img = top(&s); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0, img.0]})).unwrap()); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance's square where it is drawn"); + assert_eq!(part_at(&s, inst, (65.0, 35.0), opt), Some(vec![0]), "the nested instance's image"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 50.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline takes in the moved square and the image: {b:?}"); + + // A nested instance with a geometry effect of its own is picked where both effects draw it. + let mut s = session(); + let a = square(&mut s, 10.0); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap()); + s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "distort.transform", "params": {"moveV": 30}})).unwrap(); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 60.0), opt), Some(vec![0]), "the nested square moved by both effects"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 110.0).abs() < 0.5 && (b.y0 - 40.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "the outline follows both effects: {b:?}"); + + // Type with a fill of its own in the art is picked and outlined where the fill effect draws its + // glyphs, not in its own bounds. + let mut s = session(); + let t = id(&s.execute("text.create", &json!({"x": 10, "y": 45, "size": 40, "text": "I"})).unwrap()); + s.execute("appearance.addFill", &json!({"ids": [t.0]})).unwrap(); + let plain = { + let doc = &s.doc().unwrap().doc; + doc.node(t).unwrap().geometric_bounds().unwrap() + }; + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [t.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The type's own color still paints the glyph in place; the new fill paints it 100 pt right. + let drawn = part_outline_box(&s, inst, &[0]); + assert!(drawn.x1 > plain.x1 + 90.0 && drawn.x1 < plain.x1 + 101.0, "the outline takes in the moved glyph: {drawn:?}, plain {plain:?}"); + let glyph = drawn.x1 - 100.0 - drawn.x0; + let (x, y) = (drawn.x1 - glyph / 2.0, (drawn.y0 + drawn.y1) / 2.0); + assert_eq!(part_at(&s, inst, (x, y), opt), Some(vec![0]), "the type where the fill effect draws its glyph"); + assert_eq!(part_at(&s, inst, (plain.x0 + 1.0, plain.y0 + 1.0), opt), None, "the type's own bounds, off its glyph"); + let by_path = HitOptions { type_path_only: true, ..opt }; + assert_eq!(part_at(&s, inst, (plain.x1 - 1.5, 45.0), by_path), Some(vec![0]), "Type Object Selection by Path Only takes the baseline"); + + // A nested instance whose own effect adds only pixels (a drop shadow) is still picked where the + // outer fill effect draws its art. + let mut s = session(); + let a = square(&mut s, 10.0); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap()); + s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "stylize.dropShadow"})).unwrap(); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the shadowed nested square where it is drawn"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the shadowed nested instance's own box"); + + // An image whose fill has Convert to Shape is picked and outlined where the instance's fill + // effect moves that shape. + let mut s = session(); + place_image(&mut s); + let img = top(&s); + let frame = node(&s, img).geometric_bounds().unwrap(); + s.execute("appearance.addFill", &json!({"ids": [img.0]})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [img.0], "color": "#00ff00", "item": 0})).unwrap(); + s.execute("effect.apply", &json!({"ids": [img.0], "effect": "convertToShape.rectangle", "item": 0})).unwrap(); + let b = square(&mut s, 200.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [img.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + let c = frame.center(); + assert_eq!(part_at(&s, inst, (c.x + 100.0, c.y), opt), Some(vec![0]), "the image where its fill is drawn"); + let o = part_outline_box(&s, inst, &[0]); + assert!(o.x1 > frame.x1 + 99.0, "the outline takes in the moved fill: {o:?}, frame {frame:?}"); +} + +/// A clipping path in a dynamic symbol's art with a geometry effect of its own is picked by its +/// own geometry, and Direct Selection outlines that geometry, not the shape the effect draws. +#[test] +fn a_picked_clipping_path_is_outlined_by_its_own_geometry() { + let mut s = session(); + let content = square(&mut s, 20.0); + let clip = square(&mut s, 10.0); + s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap(); + s.execute("effect.apply", &json!({"ids": [clip.0], "effect": "path.offsetPath", "params": {"offset": 10}})).unwrap(); + let group = top(&s); + assert!(node(&s, group).clips()); + let inst = id(&s.execute("symbol.new", &json!({"name": "Clip", "ids": [group.0], "type": "dynamic"})).unwrap()); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 10.0).abs() < 0.5 && (b.x1 - 50.0).abs() < 0.5, "the clipping path's own edge: {b:?}"); +} + +/// A symbol instance in a dynamic symbol's art whose own art is a clip group takes the instance's +/// fill effect on the clip group's members, which the canvas draws moved: Direct Selection picks it +/// where its member is drawn, not where the member's own shape is, and outlines it there. +#[test] +fn a_nested_instance_of_a_clip_group_is_picked_where_the_fill_effect_draws_its_art() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let content = square(&mut s, 10.0); + let clip = id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 60})).unwrap()); + s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap(); + let group = top(&s); + assert!(node(&s, group).clips()); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [group.0]})).unwrap()); + let b = square(&mut s, 160.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The member is drawn at x 110..150, inside the clipping path. + assert_eq!(pixel(&s, 130, 30), BLUE, "the canvas draws the member moved"); + assert_ne!(pixel(&s, 30, 30), BLUE, "and not in its own place"); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance where its member is drawn"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the member's own place"); + let o = part_outline_box(&s, inst, &[0]); + assert!((o.x0 - 110.0).abs() < 0.5 && (o.x1 - 150.0).abs() < 0.5, "the outline follows the moved member: {o:?}"); +} + #[test] fn a_drag_of_a_picked_object_moves_nothing_and_says_why() { let mut s = session(); diff --git a/crates/engine/src/tests/freeform.rs b/crates/engine/src/tests/freeform.rs index 4e65c86894..99810296ef 100644 --- a/crates/engine/src/tests/freeform.rs +++ b/crates/engine/src/tests/freeform.rs @@ -283,6 +283,41 @@ fn point_commands_need_a_freeform_gradient() { assert!(s.execute("paint.freeform.addPoint", &json!({"at": [1, 1]})).is_err()); } +/// While the Live Paint Bucket is the active tool, the point and line commands that name no `ids`, +/// `id` or `item` leave a selected freeform fill as it is and report an error, as +/// `paint.freeform.get` finds no freeform gradient then. With `ids` they edit that object. `get` and +/// `selectPoint` with an index name the bucket's colors in their error. +#[test] +fn point_commands_without_a_target_leave_the_selection_alone_under_the_bucket() { + let (mut s, id) = freeform_rect(); + run(&mut s, "paint.freeform.addLine", json!({"points": [0, 1]})); + run(&mut s, "paint.freeform.selectPoint", json!({"index": 1})); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + // get and selectPoint with an index name the bucket's colors; clearing the point still works. + for (cmd, p) in [("paint.freeform.get", json!({})), ("paint.freeform.selectPoint", json!({"index": 0}))] { + let err = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(err.contains("Live Paint Bucket"), "{cmd}: {err}"); + } + run(&mut s, "paint.freeform.selectPoint", json!({"index": null})); + let before = points(&s, id); + // A bad `aligned` is reported as such, before the missing target. + let err = s.execute("paint.freeform.addPoint", &json!({"at": [150, 150], "aligned": 3})).unwrap_err().to_string(); + assert!(err.contains("aligned"), "{err}"); + for (cmd, p) in [ + ("paint.freeform.addPoint", json!({"at": [150, 150]})), + ("paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000"})), + ("paint.freeform.deletePoint", json!({"index": 0})), + ("paint.freeform.addLine", json!({"points": [1, 2]})), + ("paint.freeform.splitLine", json!({"line": 0, "segment": 0})), + ("paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000", "ids": null})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + assert_eq!(points(&s, id), before, "{cmd} {p}: the object's points"); + } + run(&mut s, "paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000", "ids": [id.0]})); + assert_ne!(points(&s, id), before, "with ids the object's point changes"); +} + /// The point and line commands refuse a point, line or segment of 2^32 + k, where k names one that /// exists, and the points and the selected point stay as they were. A 32-bit build read the number /// as k. diff --git a/crates/engine/src/tests/gradpanel.rs b/crates/engine/src/tests/gradpanel.rs index 680abfa9e8..2a757e2a90 100644 --- a/crates/engine/src/tests/gradpanel.rs +++ b/crates/engine/src/tests/gradpanel.rs @@ -51,6 +51,53 @@ fn sample_color_with_a_stop_recolours_that_stop_in_one_undo_step() { ); } +/// With `stop` and objects in `ids`, the stop is recolored in the first object's gradient, not in +/// the gradient behind the proxy: the selection's, or the Live Paint Bucket's while it is active. +#[test] +fn sample_color_with_a_stop_and_ids_recolours_the_first_given_objects_gradient() { + let mut s = session(); + let target = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + let three = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#888888"}, {"offset": 1, "color": "#000000"}]); + s.execute("paint.setFill", &json!({"gradient": {"stops": three}})).unwrap(); + let selected = rect(&mut s, 200.0, 10.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 2, "ids": [target.0]})).unwrap(); + assert_eq!(stop_hexes(&s, target, false), ["#ffffff", "#888888", "#ff0000"], "the given object's three stops"); + assert_eq!(stop_hexes(&s, selected, false), ["#ffffff", "#000000"], "the selection"); + // The bucket's solid fill, and then a two-stop gradient of its own. + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [target.0]})).unwrap(); + assert_eq!(stop_hexes(&s, target, false), ["#0000ff", "#888888", "#ff0000"], "under the bucket's solid fill"); + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#00ffff", "stop": 1, "ids": [target.0]})).unwrap(); + assert_eq!(stop_hexes(&s, target, false), ["#0000ff", "#00ffff", "#ff0000"], "under the bucket's gradient"); + // A given object without a gradient has no stop to recolor. + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [selected.0]})).unwrap(); + let err = s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [selected.0]})).unwrap_err(); + assert!(err.to_string().contains("not a gradient"), "{err}"); + // A member of a compound path: the compound path's gradient, which the edit changes. + s.select_tool("selection", ViewInfo::default()).unwrap(); + let (a, b) = (rect(&mut s, 10.0, 300.0, 50.0, 50.0), rect(&mut s, 100.0, 300.0, 50.0, 50.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects[0]; + s.execute("paint.setFill", &json!({"gradient": {"stops": three}, "ids": [compound.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [selected.0]})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 2, "ids": [a.0]})).unwrap(); + assert_eq!(stop_hexes(&s, compound, false), ["#ffffff", "#888888", "#ff0000"], "the compound path's three stops"); + // A group: the stops of its first painted object, which every painted object of the group takes. + let (c, d) = (rect(&mut s, 10.0, 400.0, 50.0, 50.0), rect(&mut s, 100.0, 400.0, 50.0, 50.0)); + s.execute("paint.setFill", &json!({"gradient": {"stops": three}, "ids": [c.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [d.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [c.0, d.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [selected.0]})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [group.0]})).unwrap(); + assert_eq!(stop_hexes(&s, c, false), ["#0000ff", "#888888", "#000000"], "the group's first object"); + assert_eq!(stop_hexes(&s, d, false), ["#0000ff", "#888888", "#000000"], "the group's other object"); +} + fn fill_geom(s: &Session, id: NodeId) -> Option { match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { Paint::Gradient(g) => g.geom, diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index 37b72efa77..967276aa5f 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -13,7 +13,8 @@ use crate::*; fn session() -> Session { let mut s = Session::new(); - s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + // A fixed created date: two sessions made in different seconds would otherwise differ in it. + s.execute("file.new", &json!({"width": 800, "height": 600, "created": 0})).unwrap(); s } diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index a75bc532bf..cf5fc3c269 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -456,6 +456,92 @@ fn a_pattern_item_adds_the_swatch_of_a_pattern_the_document_holds_without_one() assert!(!s.doc().unwrap().doc.swatches_iter().any(is_dots), "undone with the paint"); } +/// A pattern item whose art links to a global color that the document has under the same name in +/// another color keeps the item's color: the color comes in under a numbered name and the pattern +/// links to it. Used again, the pattern and that color are reused. A document whose pattern of +/// that name links to the document's own color (as pasting with Merge leaves it) reuses that one. +#[test] +fn a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color() { + let mut s = session(); + let lib = run(&mut s, "library.create", json!({}))["id"].as_str().unwrap().to_string(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + make_pattern(&mut s, &dot, "Dots"); + let a = run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Dots", "ids": [a]})); + run(&mut s, "select.set", json!({"ids": [a]})); + run(&mut s, "library.add", json!({"library": lib, "kind": "fillPattern"})); + run(&mut s, "edit.copy", json!({})); + let names = |s: &Session, base: &str| -> Vec { + let d = &s.doc().unwrap().doc; + d.swatches_iter().filter(|w| w.name.starts_with(base)).map(|w| w.name.clone()).collect() + }; + let art_link = |s: &Session, pattern: &str| match s.doc().unwrap().doc.pattern(pattern).unwrap().art[0].appearance.fill_paint() { + vectorcraft_color::Paint::Solid { swatch, color, .. } => (swatch, color.to_hex()), + p => panic!("the pattern's art is not filled with a color: {p:?}"), + }; + // A document whose Ink is red. + let red_ink = |s: &mut Session| { + run(s, "file.new", json!({"width": 300, "height": 300})); + run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let b = run(s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 80}))["id"].clone(); + run(s, "select.set", json!({"ids": [b]})); + }; + red_ink(&mut s); + let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"})); + assert_eq!(r["pattern"], "Dots", "{r}"); + assert_eq!(art_link(&s, "Dots"), (Some("Ink 2".to_string()), "#0000ff".to_string())); + assert_eq!(names(&s, "Ink"), ["Ink", "Ink 2"]); + run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots", "to": "stroke"})); + assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused"); + assert_eq!(names(&s, "Ink"), ["Ink", "Ink 2"], "the color is reused"); + // Pasted with Merge, the pattern links to the document's red Ink. + red_ink(&mut s); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + assert_eq!(art_link(&s, "Dots"), (Some("Ink".to_string()), "#ff0000".to_string())); + let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"})); + assert_eq!(r["pattern"], "Dots", "{r}"); + assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused"); + assert_eq!(names(&s, "Ink"), ["Ink"]); +} + +/// A pattern pasted with Merge whose art uses a tint of a global color is reused by its pattern +/// item after the tint swatch is deleted: the tint swatch comes back and no copy of the pattern is +/// added. +#[test] +fn a_merged_pattern_whose_tint_swatch_was_deleted_is_reused() { + let mut s = session(); + let lib = run(&mut s, "library.create", json!({}))["id"].as_str().unwrap().to_string(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]})); + make_pattern(&mut s, &dot, "Dots"); + let a = run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Dots", "ids": [a]})); + run(&mut s, "select.set", json!({"ids": [a]})); + run(&mut s, "library.add", json!({"library": lib, "kind": "fillPattern"})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 300, "height": 300})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let tints: Vec = + s.doc().unwrap().doc.swatches_iter().filter(|w| w.name != "Ink" && w.name.starts_with("Ink")).map(|w| w.name.clone()).collect(); + assert_eq!(tints.len(), 1, "the tint swatch comes with the paste: {tints:?}"); + run(&mut s, "swatch.delete", json!({"names": tints, "unlink": false})); + let b = run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 80}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [b]})); + let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"})); + assert_eq!(r["pattern"], "Dots", "{r}"); + assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused"); + let restored = s.doc().unwrap().doc.swatch(&tints[0]).map(|w| w.paint.clone()); + assert!( + matches!(&restored, Some(vectorcraft_color::Paint::Solid { swatch: Some(base), tint, .. }) if base == "Ink" && (*tint - 0.5).abs() < 1e-6), + "the tint swatch comes back as a tint of the document's Ink: {restored:?}" + ); +} + /// Gradients and patterns go out to a library file and come back; read from a file, a gradient /// with too few stops is dropped, one out of range is put in range, and a pattern whose data is /// damaged or doesn't hold its pattern fails cleanly when used. diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index feb71e40ad..60f223334c 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1736,11 +1736,17 @@ fn pathfinder_options_round_trip_and_refuse_bad_values() { assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set); let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap(); assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}"); + for (given, want) in [("10 pt", 10.0), ("0.25", 0.25)] { + let r = s.execute("object.pathfinder.options", &json!({"precision": given})).unwrap(); + assert_eq!(r["precision"], json!(want), "{given}"); + } s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap(); for bad in [ json!({"precision": 0}), json!({"precision": 11}), json!({"precision": "x"}), + json!({"precision": "1abc"}), + json!({"precision": "0.5 extra"}), json!({"precision": -1}), json!({"removeRedundantPoints": "yes"}), json!({"removeUnpainted": 1}), @@ -2067,6 +2073,23 @@ fn a_precision_set_after_a_scale_past_its_range_is_kept() { assert_eq!(s.doc().unwrap().history.undo.len(), steps); } +/// Soft Mix's Mixing Rate is compared by value: 50 over a stored 50.0 records no undo step, and 51 +/// is an edit. +#[test] +fn a_soft_mix_rate_set_to_its_value_records_no_step() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"mixingRate": 50.0}})).unwrap(); + assert_eq!(first_effect_params(&s)["mixingRate"], json!(50.0)); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"mixingRate": 50}})).unwrap(), json!({"ids": []})); + assert_eq!((first_effect_params(&s)["mixingRate"].clone(), steps(&s)), (json!(50.0), before), "50 over 50.0: no step"); + assert_ne!(s.execute("effect.setParams", &json!({"index": 0, "params": {"mixingRate": 51}})).unwrap(), json!({"ids": []})); + assert_eq!((first_effect_params(&s)["mixingRate"].clone(), steps(&s)), (json!(51), before + 1), "51 is an edit"); +} + /// A single group containing multiple overlapping paths is accepted by Crop. #[test] fn crop_operates_on_a_single_selected_group_of_paths() { diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index 01f8e76fbc..14dda53e81 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -334,7 +334,7 @@ fn replace_art_is_refused_without_changing_anything() { for (case, p, why) in [ ("no name", json!({}), "missing name".to_string()), ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`".into()), - ("no art", json!({"name": "Dots", "ids": [9999]}), "select the art for the pattern tile".into()), + ("no art", json!({"name": "Dots", "ids": []}), "select the art for the pattern tile".into()), ("painted with it", json!({"name": "Dots", "ids": [other.0]}), "art painted with `Dots` can't be its tile".into()), ("through a pattern", json!({"name": "Dots", "ids": [via.0]}), "art painted with `Dots` can't be its tile".into()), ("through a symbol", json!({"name": "Dots", "ids": [instance.0]}), "art painted with `Dots` can't be its tile".into()), @@ -359,6 +359,28 @@ fn replace_art_is_refused_without_changing_anything() { unchanged(&s, &before, steps, "while editing"); } +/// Make, Replace Pattern Art and the Repeat commands return an error, changing nothing, when an +/// `ids` entry names no object, also beside one that does: they never act on the rest alone. +#[test] +fn pattern_and_repeat_commands_refuse_an_unknown_id_without_changing_anything() { + let mut s = session(); + make_dots(&mut s); + let blue = blue_rect(&mut s); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + for (cmd, p) in [ + ("object.pattern.replaceArt", json!({"name": "Dots", "ids": [blue.0, 9999]})), + ("object.pattern.make", json!({"name": "P", "ids": [blue.0, 9999]})), + ("object.repeat.radial", json!({"ids": [blue.0, 9999]})), + ("object.repeat.grid", json!({"ids": [9999, blue.0]})), + ("object.repeat.mirror", json!({"ids": [9999]})), + ] { + let err = s.execute(cmd, &p).unwrap_err(); + assert!(err.to_string().contains("no such object id 9999"), "{cmd}: {err}"); + assert_eq!(doc(&s), &before, "{cmd}: the document stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}: no undo step"); + } +} + fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { Arc::make_mut(&mut s.doc_mut().unwrap().doc) } diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index f14be809b4..754dda7e42 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, SubPath}; -use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; +use vectorcraft_tools::{Mods, Overlay, PointerEvent, PointerKind, ToolKey}; use crate::tooling::ViewInfo; use crate::*; @@ -43,13 +43,20 @@ fn pt(x: f64, y: f64) -> Point { } fn press(s: &mut Session, pts: &[(f64, f64)]) { - let v = view(); - s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap(); + press_in(s, pts, view()); +} + +fn press_in(s: &mut Session, pts: &[(f64, f64)], v: ViewInfo) { + press_with(s, pts, v, Mods::default()); +} + +fn press_with(s: &mut Session, pts: &[(f64, f64)], v: ViewInfo, m: Mods) { + s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m), v).unwrap(); for &(x, y) in &pts[1..] { - s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y).with_mods(m), v).unwrap(); } let l = pts[pts.len() - 1]; - s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m), v).unwrap(); } fn click(s: &mut Session, x: f64, y: f64) { @@ -505,6 +512,311 @@ fn a_click_on_an_open_end_continues_the_path() { assert_eq!(ends, [pt(200.0, 100.0), pt(100.0, 100.0), pt(100.0, 200.0)]); } +/// With Smart Guides on, a click near another path's anchor puts the point on that anchor; with +/// them off, the point stays where the click was. +#[test] +fn a_point_snaps_to_a_smart_guide() { + for (guides, want) in [(true, pt(300.0, 300.0)), (false, pt(302.0, 301.0))] { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 500, "y2": 450})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + quick_pen(&mut s); + let v = ViewInfo { smart_guides: guides, ..Default::default() }; + press_in(&mut s, &[(100.0, 100.0)], v); + press_in(&mut s, &[(302.0, 301.0)], v); + let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap(); + assert!(drawn.1.subpaths[0].anchors.last().unwrap().p.distance(want) < 1e-9, "{guides}"); + } +} + +/// A point 100 pt from (200, 100) and 30.5° below the +x direction a path from (100, 100) ends in: +/// a continuous arc to it sweeps 61°. +fn arc_end_61() -> Point { + let half = 30.5f64.to_radians(); + pt(200.0 + 100.0 * half.cos(), 100.0 + 100.0 * half.sin()) +} + +/// The protractor's 60° tick for the arc to [`arc_end_61`]: on the same circle, a 60° sweep. +fn tick_60() -> Point { + let r = 50.0 / 30.5f64.to_radians().sin(); + pt(200.0 + r * 30f64.to_radians().cos(), 100.0 + r * 30f64.to_radians().sin()) +} + +/// A path from (100, 100) to (200, 100) drawn with Quick Pen, the action then a continuous arc. +fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) { + quick_pen(s); + press_in(s, &[(100.0, 100.0)], v); + press_in(s, &[(200.0, 100.0)], v); + key(s, ToolKey::AltTap); +} + +/// The last point of the path the tool drew (any other path is a two-point line). +fn drawn_end(s: &Session) -> Point { + let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap(); + drawn.1.subpaths[0].anchors.last().unwrap().p +} + +/// A continuous arc dragged to end 61° round goes onto the protractor's 60° tick with Smart Guides +/// on, also with Shift held, which does not constrain Quick Pen points; with them off it ends at +/// the pointer. A Smart Guide in reach (another path's anchor) wins over the tick, also with its +/// label hidden, and so do Snap to Grid and Snap to Pixel. +#[test] +fn a_continuous_arc_end_snaps_to_the_protractor() { + let at = arc_end_61(); + let anchor = pt(at.x + 0.2, at.y + 0.15); + let fresh = session(); + let g = &fresh.doc().unwrap().doc.grid; + let step = g.spacing / g.subdivisions.max(1) as f64; + let on_grid = pt((at.x / step).round() * step, (at.y / step).round() * step); + let on_pixel = pt(at.x.round(), at.y.round()); + let shift = Mods { shift: true, ..Default::default() }; + // (Smart Guides, the other path, Snap to Grid, Snap to Pixel, Anchor/Path Labels, mods, where + // the end goes, the pointer) + let cases = [ + (true, false, false, false, true, Mods::default(), tick_60(), at), + (true, false, false, false, true, shift, tick_60(), at), + (false, false, false, false, true, Mods::default(), at, at), + (true, true, false, false, true, Mods::default(), anchor, at), + (true, false, true, false, true, Mods::default(), on_grid, on_grid), + (true, false, false, true, true, Mods::default(), on_pixel, on_pixel), + // Exactly on the anchor, which shows no guide with the labels off. + (true, true, false, false, false, Mods::default(), anchor, anchor), + ]; + for (guides, other, grid, pixel, labels, m, want, pointer) in cases { + let mut s = session(); + s.prefs.anchor_path_labels = labels; + if other { + s.execute("shape.line", &json!({"x1": anchor.x, "y1": anchor.y, "x2": 600, "y2": anchor.y})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + } + let v = ViewInfo { smart_guides: guides, snap_to_grid: grid, snap_to_pixel: pixel, ..Default::default() }; + continuous_arc_after_a_line(&mut s, v); + press_with(&mut s, &[(280.0, 140.0), (pointer.x, pointer.y)], v, m); + let end = drawn_end(&s); + assert!(end.distance(want) < 1e-6, "{guides} {other} {grid} {pixel} {labels} {m:?}: {end:?}"); + } +} + +/// With Smart Guides on, a click without a drag puts a continuous arc's end on the protractor's +/// tick; after Alt switches to a sharp-corner arc, a click at the same place puts the end at the +/// pointer. +#[test] +fn a_click_puts_a_continuous_arc_end_on_a_tick() { + let at = arc_end_61(); + let v = ViewInfo::default(); + for (taps, want) in [(0, tick_60()), (1, at)] { + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + for _ in 0..taps { + key(&mut s, ToolKey::AltTap); + } + press_in(&mut s, &[(at.x, at.y)], v); + let end = drawn_end(&s); + assert!(end.distance(want) < 1e-6, "{taps}: {end:?}"); + } +} + +/// Alt tapped during a press moves the end of the piece for the new action at once, with no +/// further drag: a continuous arc's end on the 60° tick goes to the pointer once the piece is a +/// sharp-corner arc, after a drag and after a press that has not dragged, and a line's end at the +/// pointer goes onto the tick once the piece is a continuous arc. +#[test] +fn an_alt_tap_during_a_press_moves_the_end_for_the_new_action() { + let at = arc_end_61(); + let v = ViewInfo::default(); + // (drag first, Alt taps before the press, the end before Alt, the end after it) + for (drag, taps, before, after) in [(true, 0, tick_60(), at), (false, 0, tick_60(), at), (true, 2, at, tick_60())] { + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + for _ in 0..taps { + key(&mut s, ToolKey::AltTap); + } + let first = if drag { (280.0, 140.0) } else { (at.x, at.y) }; + s.pointer(&PointerEvent::new(PointerKind::Down, first.0, first.1), v).unwrap(); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, at.x, at.y), v).unwrap(); + } + assert!(drawn_end(&s).distance(before) < 1e-6, "{drag} {taps}: {:?}", drawn_end(&s)); + s.tool_key(ToolKey::AltTap, Mods::default(), v).unwrap(); + assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} after Alt: {:?}", drawn_end(&s)); + s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), v).unwrap(); + assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} placed: {:?}", drawn_end(&s)); + } +} + +/// After a click puts a continuous arc's end on a tick away from the pointer, no preview runs from +/// the placed end back to where the pointer was; the next move shows the preview again. +#[test] +fn a_click_on_a_tick_leaves_no_preview_back_to_the_pointer() { + let at = arc_end_61(); + let v = ViewInfo::default(); + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap(); + press_in(&mut s, &[(at.x, at.y)], v); + assert!(drawn_end(&s).distance(tick_60()) < 1e-6); + let label = |s: &mut Session| s.overlays(v).iter().any(|o| matches!(o, Overlay::Measure { .. })); + assert!(!label(&mut s), "no distance label back to the pointer"); + s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 300.0), v).unwrap(); + assert!(label(&mut s)); +} + +/// Hovering near a tick as a continuous arc puts the distance label beside the tick; after Alt +/// switches the action, the same hover puts it beside the pointer. +#[test] +fn a_hover_snaps_to_a_tick_only_for_a_continuous_arc() { + let at = arc_end_61(); + let tick = tick_60(); + let v = ViewInfo::default(); + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap(); + let label = |s: &mut Session| { + s.overlays(v).iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }) + }; + let off = label(&mut s).unwrap() - tick; + assert!(off.x > 0.0 && (off.x - off.y).abs() < 1e-9, "the label sits diagonally off the tick: {off:?}"); + for _ in 0..2 { + key(&mut s, ToolKey::AltTap); + assert!((label(&mut s).unwrap() - off).distance(at) < 1e-9, "{:?}", s.tool_options()["action"]); + } +} + +/// A hover made with Smart Guides off shows nothing once they are turned on under the still +/// pointer, so it shows no tick that a click would not use (another path's anchor under the +/// pointer takes the click). The next move shows the hover again, its label beside the anchor; +/// once Smart Guides are turned off again, its guides are hidden with it, also after a click. +#[test] +fn a_hover_shows_nothing_after_smart_guides_change() { + let at = arc_end_61(); + let off = ViewInfo { smart_guides: false, ..Default::default() }; + let on = ViewInfo::default(); + let mut s = session(); + s.execute("shape.line", &json!({"x1": at.x, "y1": at.y, "x2": 600, "y2": at.y})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + continuous_arc_after_a_line(&mut s, off); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), off).unwrap(); + let label = |s: &mut Session, v: ViewInfo| { + s.overlays(v).iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }) + }; + assert!(label(&mut s, off).is_some()); + assert_eq!(label(&mut s, on), None, "the hover from before the change shows nothing"); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap(); + let off_anchor = label(&mut s, on).unwrap() - at; + assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}"); + let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); + assert!(!only_points(&mut s, on)); + assert!(only_points(&mut s, off), "only the path's points show"); + // A click before the pointer moves does not bring the stale hover back. + press_in(&mut s, &[(400.0, 300.0)], off); + assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click"); +} + +/// While the pointer hovers, the tool asks the canvas to hover it again when the view, the document +/// or the selection changes under a still pointer, so the snapped point follows the art; a press +/// stops it until the next move. +#[test] +fn a_hover_is_hovered_again_when_the_art_changes() { + let mut s = session(); + continuous_arc_after_a_line(&mut s, view()); + assert!(!s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap(); + assert!(s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 180.0), view()).unwrap(); + assert!(!s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap(); + assert!(!s.tool_wants_rehover()); +} + +/// A hover on the path's last point, which another path's anchor shares, shows that anchor's Smart +/// Guide; after Smart Guides are turned off, a click there adds nothing and the guide stays hidden +/// while the button is held and after it is let go. +#[test] +fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() { + let off = ViewInfo { smart_guides: false, ..Default::default() }; + let on = ViewInfo::default(); + let mut s = session(); + s.execute("shape.line", &json!({"x1": 200, "y1": 100, "x2": 200, "y2": 400})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + continuous_arc_after_a_line(&mut s, on); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap(); + let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); + assert!(!only_points(&mut s, on), "the anchor's guide shows"); + assert!(only_points(&mut s, off)); + let steps = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), off).unwrap(); + assert!(only_points(&mut s, off), "the guide stays hidden while the button is held"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 100.0), off).unwrap(); + assert_eq!(undo_steps(&s), steps, "the click adds nothing"); + assert!(only_points(&mut s, off), "the guide stays hidden"); +} + +/// While a press drags an arc, the tool shows its protractor; while it drags a line, it shows none. +#[test] +fn an_arc_drag_shows_the_protractor() { + let mut s = session(); + quick_pen(&mut s); + let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); + for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] { + key(&mut s, ToolKey::Escape); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 150.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 180.0), view()).unwrap(); + assert_eq!(protractors(&mut s), shown, "{action}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap(); + } +} + +/// While hovering, the piece the next click adds shows its protractor beside the rubber band, and +/// neither shows with the Pen tool's rubber band preference off; a line has no protractor. (Smart +/// Guides are off, so no guide paths show.) +#[test] +fn a_hovered_arc_shows_the_protractor_with_the_rubber_band() { + for (rubber_band, action, paths) in [(true, "continuousArc", 2), (true, "line", 1), (false, "continuousArc", 0)] { + let mut s = session(); + s.prefs.pen_rubber_band = rubber_band; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap(); + let shown = s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); + assert_eq!(shown, paths, "{rubber_band} {action}"); + } +} + +/// With Measurement Labels on, hovering after the path's last point shows the distance label +/// beside the pointer; with them off, no label shows. +#[test] +fn hovering_shows_the_distance_label() { + for labels in [true, false] { + let mut s = session(); + s.prefs.measurement_labels = labels; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 200.0), view()).unwrap(); + let o = s.overlays(view()); + let label = o.iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }); + assert_eq!(label.is_some(), labels); + if let Some(p) = label { + assert!(p.x > 300.0 && p.y > 200.0, "beside the pointer: {p:?}"); + } + } +} + /// `path.quickPen` makes a new path with the current paint, or a black stroke without any. #[test] fn path_quick_pen_makes_a_stroked_path() { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 7653dc083d..25ccb3bcfb 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -418,7 +418,8 @@ fn script_file_encoding_binary_ascii() { } /// A script's own folder is only read: writing there, and anywhere it was not given, is refused, -/// and with nobody to ask its file dialogs give `null`. Aliases and `execute` are not available. +/// and with nobody to ask its file dialogs give `null`. Setting `hidden` and `createAlias` are +/// refused there too, and `execute` is not available. #[test] fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { let base = folder("writes"); @@ -454,10 +455,10 @@ fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { null, false, "Script files cannot be opened in another application", - "Script file hidden setting cannot be changed", + DENIED, false, false, - "Script files cannot make aliases", + DENIED, "" ]]) ); @@ -465,6 +466,7 @@ fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { assert_eq!(r["written"], json!([])); assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep"); assert!(!base.join("main/new.txt").exists() && !base.join("main/made").exists() && !base.join("main/c.txt").exists()); + assert!(!base.join("main/.keep.txt").exists() && std::fs::symlink_metadata(base.join("main/l")).is_err()); assert!(!Path::new(&outside).exists()); let _ = std::fs::remove_dir_all(base); } @@ -693,6 +695,250 @@ fn a_renamed_file_names_its_old_and_new_paths_in_written() { let _ = std::fs::remove_dir_all(base); } +#[cfg(unix)] +const NOT_FOUND: &str = "Script file does not exist"; +#[cfg(unix)] +const NOT_REGULAR: &str = "Script file is not a regular file"; +#[cfg(unix)] +const TAKEN: &str = "Script file name is already in use"; + +/// On Unix setting `hidden` renames a file with one dot added or its leading dots taken off, and the +/// object takes the new path: a file it has open stays open and is written at the new path, a file +/// already as asked keeps its name, and a name in use, a name of dots alone and a folder are refused. +#[cfg(unix)] +#[test] +fn script_file_hidden_renames_the_file_with_a_leading_dot() { + let base = folder("hidden"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, u = new File(d + '/u.txt'); u.open('w'); u.write('kept');\n\ + var before = u.fsName; u.hidden = true;\n\ + var out = [u.name, u.hidden, u.error, new File(d + '/.u.txt').hidden, new File(before).exists];\n\ + u.hidden = true; out.push(u.name, u.error, u.write('+'), u.close()); u.open('r'); out.push(u.read()); u.close();\n\ + u.hidden = false; out.push(u.name, u.hidden, new File(d + '/.u.txt').exists);\n\ + var dots = new File(d + '/...'); dots.open('w'); dots.close(); dots.hidden = false; out.push(dots.error, dots.exists);\n\ + var v = new File(d + '/v.txt'), w = new File(d + '/.v.txt'); v.open('w'); v.close(); w.open('w'); w.write('w'); w.close();\n\ + v.hidden = true; out.push(v.error, v.name, w.length);\n\ + var g = new Folder(d + '/g'); g.create(); var gf = new File(g.fsName); gf.hidden = true; out.push(gf.error, g.exists);\n\ + vc.log(out); vc.log(d);", + ) + .unwrap(); + let no_hidden = "Script file hidden setting cannot be changed"; + assert_eq!( + r["log"][0], + json!([ + ".u.txt", + true, + "", + true, + false, + ".u.txt", + "", + true, + true, + "kept+", + "u.txt", + false, + false, + no_hidden, + true, + TAKEN, + "v.txt", + 1, + NOT_REGULAR, + true + ]) + ); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + let mut names: Vec = std::fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, ["...", ".v.txt", "g", "u.txt", "v.txt"]); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for name in ["u.txt", ".u.txt"] { + assert!(written.contains(&d.join(name).to_string_lossy().as_ref()), "{name} in {written:?}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Setting `hidden` gives the file a new name, which must be a place the script may write too: a +/// file allowed on its own in a save dialog keeps its name. +#[cfg(unix)] +#[test] +fn script_file_hidden_needs_the_new_name_to_be_writable() { + let base = folder("hiddengrant"); + let picked = base.join("picked/s.txt"); + write(&picked, b"s"); + let mut s = with_data(&base); + start_framed( + &mut s, + &base, + "var f = File.saveDialog('s'); f.hidden = true; var out = [f.error, f.name, f.hidden]; out.push(f.rename('t.txt'), f.error, f.name); vc.log(out);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[DENIED, "s.txt", false, false, DENIED, "s.txt"]])); + assert!(picked.exists() && !base.join("picked/.s.txt").exists() && !base.join("picked/t.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix `createAlias` makes a link, in a place the script may write, to a file it may read: the +/// link is an alias that resolves to the file and reads it, `hidden` tells of the link's own name, +/// setting `hidden` and `remove` change the link alone, and writing through it to a file the script +/// may only read is refused. A link that leads out of the script's places afterward reads nothing. +#[cfg(unix)] +#[test] +fn script_file_create_alias_links_to_a_file_the_script_may_read() { + let base = folder("alias"); + write(&base.join("main/keep.txt"), b"keep"); + write(&base.join("main/.hid.txt"), b"hid"); + write(&base.join("secret.txt"), b"secret"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, k = new File('keep.txt'), l = new File(d + '/l');\n\ + var out = [l.createAlias(k), l.error, l.alias, l.resolve().fsName === k.fsName, l.hidden, k.alias];\n\ + l.open('r'); out.push(l.read()); l.close();\n\ + out.push(l.open('w'), l.error, l.open('a'), l.error);\n\ + var h = new File(d + '/h'); out.push(h.createAlias('.hid.txt'), h.hidden, h.resolve().name);\n\ + l.hidden = true; out.push(l.name, l.alias, l.hidden, k.exists, k.hidden);\n\ + out.push(l.remove(), l.exists, k.exists); vc.log(out); vc.log(d);", + ) + .unwrap(); + assert_eq!( + r["log"][0], + json!([ + true, "", true, true, false, false, "keep", false, DENIED, false, DENIED, true, false, ".hid.txt", ".l", true, true, true, false, true, + false, true + ]) + ); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep"); + assert!(std::fs::symlink_metadata(d.join("l")).is_err() && std::fs::symlink_metadata(d.join(".l")).is_err()); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(written.contains(&d.join("l").to_string_lossy().as_ref()), "{written:?}"); + std::fs::remove_file(d.join("h")).unwrap(); + std::os::unix::fs::symlink(base.join("secret.txt"), d.join("h")).unwrap(); + let r = run_in(&mut s, &base, "var h = new File(Folder.userData.fsName + '/h'); vc.log([h.open('r'), h.error, h.alias, h.resolve()]);").unwrap(); + assert_eq!(r["log"], json!([[false, DENIED, false, null]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `createAlias` makes nothing where the script may only read or may not go at all, at a name in use +/// (a link that leads nowhere included), to a folder, to a file outside its places, in the settings +/// folder or behind a link that leads out, to a file that is not there, or without a target. +#[cfg(unix)] +#[test] +fn script_file_create_alias_is_refused_outside_the_scripts_places() { + let base = folder("aliasdenied"); + write(&base.join("main/keep.txt"), b"keep"); + write(&base.join("secret.txt"), b"secret"); + write(&base.join("main/settings/Script Grants.json"), b"{\"version\": 1, \"grants\": []}"); + std::fs::create_dir_all(base.join("main/sub")).unwrap(); + std::fs::create_dir_all(base.join("elsewhere")).unwrap(); + std::os::unix::fs::symlink(base.join("secret.txt"), base.join("main/out.txt")).unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("main/settings/Script Data")); + let d = PathBuf::from(run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap()["log"][0].as_str().unwrap()); + write(&d.join("taken"), b"t"); + std::os::unix::fs::symlink(base.join("nowhere"), d.join("dangling")).unwrap(); + let text = format!( + "var d = Folder.userData.fsName, out = [];\n\ + function a(at, to) {{ var f = new File(at); out.push(f.createAlias(to), f.error); }}\n\ + a('own', 'keep.txt'); a(d + '/taken', 'keep.txt'); a(d + '/dangling', 'keep.txt'); a(d + '/dir', 'sub');\n\ + a(d + '/s', {:?}); a(d + '/g', 'settings/Script Grants.json'); a(d + '/o', 'out.txt'); a(d + '/n'); a(d + '/m', 'missing.txt');\n\ + a({:?}, 'keep.txt'); vc.log(out);", + base.join("secret.txt").to_string_lossy(), + base.join("elsewhere/x").to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!( + r["log"], + json!([[ + false, + DENIED, + false, + TAKEN, + false, + TAKEN, + false, + NOT_REGULAR, + false, + DENIED, + false, + DENIED, + false, + DENIED, + false, + NOT_FOUND, + false, + NOT_FOUND, + false, + DENIED + ]]) + ); + assert!(std::fs::symlink_metadata(base.join("main/own")).is_err()); + assert_eq!(std::fs::read_dir(base.join("elsewhere")).unwrap().count(), 0); + for name in ["dir", "s", "g", "o", "n", "m"] { + assert!(std::fs::symlink_metadata(d.join(name)).is_err(), "{name}"); + } + assert_eq!(std::fs::read(d.join("taken")).unwrap(), b"t"); + assert_eq!(std::fs::read_link(d.join("dangling")).unwrap(), base.join("nowhere")); + assert_eq!(r["written"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// A link put in place of the folder an alias goes in, after the alias's place was looked up, does +/// not leave a new link where it leads. +#[cfg(unix)] +#[test] +fn script_file_alias_is_not_left_behind_a_folder_replaced_by_a_link() { + let base = folder("aliasrace"); + write(&base.join("main/keep.txt"), b"keep"); + let outside = base.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + let mut s = with_data(&base); + let to = outside.clone(); + crate::script::files::BEFORE_ALIAS_LINK.with(|h| { + *h.borrow_mut() = Some(Box::new(move |at: &Path| { + let sub = at.parent().unwrap(); + std::fs::rename(sub, sub.with_file_name("moved")).unwrap(); + std::os::unix::fs::symlink(&to, sub).unwrap(); + })); + }); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName; new Folder(d + '/sub').create(); var l = new File(d + '/sub/l'); vc.log([l.createAlias('keep.txt'), l.error]);", + ); + crate::script::files::BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take()); + assert_eq!(r.unwrap()["log"], json!([[false, DENIED]])); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "no link is left outside the script's places"); + let _ = std::fs::remove_dir_all(base); +} + +/// Where a hidden file is not one whose name starts with a dot, setting `hidden` and `createAlias` +/// set `error` and change nothing. +#[cfg(not(unix))] +#[test] +fn script_file_hidden_and_aliases_are_refused_off_unix() { + let base = folder("hiddenoff"); + write(&base.join("main/keep.txt"), b"keep"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, u = new File(d + '/u.txt'); u.open('w'); u.close(); u.hidden = true; var out = [u.error, u.name];\n\ + var l = new File(d + '/l'); out.push(l.createAlias('keep.txt'), l.error, l.exists); vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([["Script file hidden setting cannot be changed", "u.txt", false, "Script files cannot make aliases", false]])); + let _ = std::fs::remove_dir_all(base); +} + /// The open modes, the encodings that cannot hold a character, `copy` over a file, `remove` of a /// folder only when it is empty, `rename` refusing a name in use, `create`, and setting `length` and /// `readonly`. @@ -1213,6 +1459,35 @@ fn script_file_rename_does_not_move_the_settings_folder() { let _ = std::fs::remove_dir_all(base); } +/// In a folder granted in a file dialog, a file is not renamed to the name of the settings folder, +/// and on Unix setting `hidden` does not give it that name either. +#[test] +fn script_file_rename_does_not_take_the_settings_folders_name() { + let base = folder("renamein"); + write(&base.join("cfg"), b"c"); + write(&base.join("x.txt"), b"x"); + let mut s = Session::new(); + s.attach_script_data(base.join(".cfg/Script Data")); + let hide = + if cfg!(unix) { "var h = new File(p.fsName + '/cfg'); h.hidden = true; out.push(h.error, h.name);" } else { "out.push(DENIED, 'cfg');" }; + let denied = format!("var DENIED = {DENIED:?};"); + start_framed( + &mut s, + &base, + &format!( + "{denied} var p = Folder.selectDialog('p'), x = new File(p.fsName + '/x.txt'), out = [x.rename('.cfg'), x.error, x.name]; {hide} vc.log(out);" + ), + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED, "x.txt", DENIED, "cfg"]])); + assert!(!base.join(".cfg").is_file()); + assert_eq!(std::fs::read(base.join("x.txt")).unwrap(), b"x"); + assert_eq!(std::fs::read(base.join("cfg")).unwrap(), b"c"); + let _ = std::fs::remove_dir_all(base); +} + /// Where case does not matter, a folder named in another case is still the folder that holds the /// settings folder, or the settings folder itself: it is not renamed or removed. #[cfg(any(windows, target_os = "macos"))] diff --git a/crates/engine/src/tests/simplify_part.rs b/crates/engine/src/tests/simplify_part.rs index f3ab93f274..82f6cdc628 100644 --- a/crates/engine/src/tests/simplify_part.rs +++ b/crates/engine/src/tests/simplify_part.rs @@ -122,34 +122,87 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() { assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); } +/// The points of a closed 80-gon of radius 100 round (300, 300), starting at (400, 300). +fn eighty_gon() -> Vec<(f64, f64)> { + (0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect() +} + /// On a closed 80-gon, a run from anchor 70 through the start point to anchor 10 simplifies as one -/// run: anchor 0 goes, anchors 11–69 stay exactly as they were (the path now starts at anchor 10), -/// anchors 10 and 70 stay where they were with their outer handles, and the path stays closed. +/// run: anchor 0 goes, and the path starts at a new anchor where the refitted run passes nearest +/// it; anchors 11–69 stay exactly as they were, anchors 10 and 70 stay where they were with their +/// outer handles, the path stays closed, and the refitted run stays direct-selected. #[test] fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() { let mut s = session(); - let pts: Vec<(f64, f64)> = - (0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect(); - let id = polyline(&mut s, &pts, true); + let id = polyline(&mut s, &eighty_gon(), true); let original = path_of(&s, id).subpaths[0].clone(); select_anchors(&mut s, id, &[(70, 79), (0, 10)]); s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap(); let sp = path_of(&s, id).subpaths[0].clone(); assert!(sp.closed); assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len()); - assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run"); - assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); - assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); - assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); - for i in 0..60 { - assert_eq!(sp.segment(i), original.segment(10 + i)); - } + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt"); let n = sp.anchors.len(); - assert!(worst_offset(&original, (70..80).chain(0..10), &sp, 60..n) <= 1.0 + 1e-6); - let sel: BTreeSet<_> = std::iter::once((0, 0)).chain((60..n).map(|i| (0, i))).collect(); + let k = sp.anchors.iter().position(|a| a.p == original.anchors[10].p).unwrap(); + let mut turned = sp.clone(); + turned.anchors.rotate_left(k); + assert_eq!(turned.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); + assert_eq!((turned.anchors[0].p, turned.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); + assert_eq!((turned.anchors[60].p, turned.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); + for i in 0..60 { + assert_eq!(turned.segment(i), original.segment(10 + i)); + } + assert!(worst_offset(&original, (70..80).chain(0..10), &turned, 60..n) <= 1.0 + 1e-6); + let sel: BTreeSet<_> = (0..=k).chain(k + 60..n).map(|i| (0, i)).collect(); assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); } +/// Smooth of a direct-selected run across the start of a closed 80-gon starts the path near where it +/// started too, with fewer anchors. +#[test] +fn smoothing_a_run_across_the_start_keeps_the_start() { + let mut s = session(); + let id = polyline(&mut s, &eighty_gon(), true); + let original = path_of(&s, id).subpaths[0].clone(); + select_anchors(&mut s, id, &[(70, 79), (0, 10)]); + s.execute("object.path.smooth", &json!({"level": 50})).unwrap(); + let sp = path_of(&s, id).subpaths[0].clone(); + assert!(sp.closed && sp.anchors.len() < 80, "{}", sp.anchors.len()); + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", sp.anchors[0].p); +} + +/// A dashed closed path keeps its start, where its dashes begin, through Simplify and through +/// Smooth: a loop of radius 50 round (300, 300) with a needle out to (550, 300), starting on the far +/// side of the loop at (250, 300). Its stroke stays as it was, and each command is one undo step. +#[test] +fn a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth() { + let mut s = session(); + let at = |deg: f64| (300.0 + 50.0 * deg.to_radians().cos(), 300.0 + 50.0 * deg.to_radians().sin()); + let pts: Vec<(f64, f64)> = + (0..=20).map(|i| at(180.0 + 8.95 * f64::from(i))).chain([(550.0, 300.0)]).chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))).collect(); + let id = polyline(&mut s, &pts, true); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 2, "dash": [10, 5]})).unwrap(); + let stroke = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.clone(); + let style = stroke(&s); + let original = path_of(&s, id).subpaths[0].clone(); + // (command, params, how far the start may move: Simplify's tolerance, or Smooth's smoothing and tolerance) + let commands = [("object.path.simplify", json!({"tolerance": 1}), 1.0 + 1e-9), ("object.path.smooth", json!({"level": 50}), 5.0)]; + for (command, params, limit) in commands { + let steps = undo_len(&s); + s.execute(command, ¶ms).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "{command}"); + let sp = path_of(&s, id).subpaths[0].clone(); + assert!(sp.closed && sp.anchors.len() < original.anchors.len(), "{command}: {}", sp.anchors.len()); + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= limit, "{command}: the start moved {moved} pt, to {:?}", sp.anchors[0].p); + assert_eq!(stroke(&s), style, "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id).subpaths[0], original, "{command}"); + } +} + /// Segments picked with the Direct Selection tool simplify the same way, and stay picked as /// segments. #[test] diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 8036bf04c3..5d94eecc69 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -516,6 +516,978 @@ fn a_library_pattern_keeps_its_global_color_when_the_document_has_that_name_in_a assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}"); } +/// A library with pattern swatch `Tiles`, whose pattern `Squares` is filled with global color +/// `Ink` (#0000ff), loaded into `s`, which is then left in a new document whose own global `Ink` +/// is #ff0000 → the library's id. The library document's square painted with `Tiles` is on the +/// clipboard. +fn squares_library_and_a_red_ink(s: &mut Session) -> Value { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + s.edit("Pattern", |d, _| { + let ink = Paint::Solid { color: Color::rgb8(0, 0, 0xff), swatch: Some("Ink".into()), tint: 1.0 }; + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0)); + let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0)); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) }); + d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false }); + Ok(()) + }) + .unwrap(); + let b64 = run(s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + let r = run(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(s, "select.set", json!({"ids": [r]})); + run(s, "edit.copy", json!({})); + run(s, "file.new", json!({"width": 100, "height": 100})); + run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + id +} + +/// The names of the swatches of `s`'s document that are `base` or a numbered copy of it. +fn named_after(s: &Session, base: &str) -> Vec { + let copy = |n: &str| n == base || n.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| r.bytes().all(|b| b.is_ascii_digit())); + doc(s).swatches_iter().filter(|w| copy(&w.name)).map(|w| w.name.clone()).collect() +} + +/// A library color that the document has as a numbered copy of the same color ("Ink 2", brought by +/// the pattern added with it before) is that copy: adding the pattern and the color again adds +/// nothing. +#[test] +fn adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]})); + assert_eq!(r["added"], json!(["Tiles", "Ink 2"]), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", "Ink 2"])), "{again}"); + assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]); +} + +/// The colors a library pattern brings with its art are listed with the swatches added, the +/// numbered ones included, when the call adds the pattern swatch alone. +#[test] +fn the_colors_a_library_pattern_brings_are_listed_as_added() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]); + assert_eq!(r["added"], json!(["Tiles", "Ink 2"]), "{r}"); +} + +/// A library pattern that is already in the document with its art linked to the document's own +/// color of that name (as pasting with Merge leaves it) is that pattern: adding its swatch adds no +/// numbered copy of the pattern or of the color. +#[test] +fn a_library_pattern_linked_to_the_documents_own_color_is_not_added_again() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + assert_eq!(doc(&s).patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Squares"]); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(doc(&s).patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Squares"], "{r}"); + assert_eq!(named_after(&s, "Ink"), ["Ink"], "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}"); +} + +/// With `apply`, the color picked first is the one applied, even when a pattern added in the same +/// call brings a numbered copy of its name. +#[test] +fn apply_paints_with_the_picked_color_not_one_a_pattern_brought() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + // The document's Ink is the library's color as a process color. + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"})); + assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"], "{r}"); + // The picked global color is not the process one: it comes in numbered, and the pattern's art + // takes it. + assert_eq!(r["applied"], "Ink 2", "{r}"); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}"); + // A picked color the document already has is applied, not the pattern added after it. + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"})); + assert_eq!((&r["existing"], &r["applied"]), (&json!(["Ink"]), &json!("Ink")), "{r}"); +} + +/// A numbered copy that another swatch of the same name hides (the document finds the first of a +/// name) is not taken for a library color, even when it has that color. +#[test] +fn a_hidden_numbered_copy_is_not_taken_for_a_library_color() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.newGroup", json!({"name": "Blues", "swatches": ["Ink 2"]})); + s.edit("Green", |d, _| { + let green = Paint::Solid { color: Color::rgb8(0, 0xff, 0), swatch: None, tint: 1.0 }; + d.swatches.push(vectorcraft_color::Swatch { name: "Ink 2".into(), paint: green, global: true, spot: false }); + Ok(()) + }) + .unwrap(); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!(r["existing"], json!([]), "{r}"); + let name = r["added"][0].as_str().unwrap_or_default().to_string(); + let blue = doc(&s).swatch(&name).and_then(|w| w.paint.color()).map(|c| c.to_hex()); + assert_eq!(blue.as_deref(), Some("#0000ff"), "{r}"); +} + +/// The global color the swatch `name` of `s`'s document is a tint of. +fn tint_base(s: &Session, name: &str) -> Option { + match doc(s).swatch(name).map(|w| &w.paint) { + Some(Paint::Solid { swatch, .. }) => swatch.clone(), + _ => None, + } +} + +/// A library with global color `Ink` (#0000ff) and its tint `Ink half` loaded into `s`, which is +/// then left in a new document whose own global `Ink` is #ff0000 → the library's id. +fn tinted_ink_library_and_a_red_ink(s: &mut Session) -> Value { + run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let b64 = run(s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(s, "file.new", json!({"width": 100, "height": 100})); + run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + id +} + +/// A library tint added with its global color, which comes in under a numbered name, is a tint of +/// that numbered color, not of the document's own color of the library color's name. +#[test] +fn a_library_tint_follows_its_color_to_its_numbered_name() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + assert_eq!(r["added"], json!(["Ink 2", "Ink half"]), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 2", "Ink half"])), "{again}"); +} + +/// A library tint picked before its global color still follows the color to its numbered name. +#[test] +fn a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Ink"]})); + assert_eq!(r["added"], json!(["Ink half", "Ink 2"]), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Ink"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half", "Ink 2"])), "{again}"); +} + +/// A library tint added without its global color finds the numbered copy an earlier add brought. +#[test] +fn a_library_tint_added_alone_finds_its_colors_numbered_copy() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(r["added"], json!(["Ink half"]), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}"); +} + +/// A library tint added alone links to the numbered copy of its own color, not to another library +/// color's copy of the same paint. +#[test] +fn a_library_tint_added_alone_skips_another_library_colors_copy() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 3"]), "{r}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 3"), "{r}"); +} + +/// A library tint added alone finds its color's numbered copy when a color group of the document +/// has the color's name. +#[test] +fn a_library_tint_finds_its_colors_copy_beside_a_group_of_its_name() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + run(&mut s, "swatch.newGroup", json!({"name": "Ink", "colors": ["#123456"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{r}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); +} + +/// A library pattern whose art uses a tint of a library color added earlier in the same call +/// does not bring a second copy of that tint, also when the call does not pick the color. +#[test] +fn a_pattern_after_its_tint_in_one_call_does_not_copy_the_tint() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + for names in [json!(["Ink", "Ink half", "Squares"]), json!(["Ink half", "Ink", "Squares"]), json!(["Ink half", "Squares"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{names}: {r}"); + } +} + +/// A library color added under a numbered name skips the names of the library's other swatches, +/// so adding it again finds that copy. +#[test] +fn a_library_colors_copy_skips_the_librarys_other_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!(r["added"], json!(["Ink 3"]), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 3"])), "{again}"); +} + +/// A library tint links to a global color even when the document has a process color of the same +/// name and paint, which the picked library color matches: the pattern's art brings the global one. +#[test] +fn a_library_tint_links_to_the_global_color_a_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + for names in [json!(["Ink", "Tiles", "Ink half"]), json!(["Ink", "Ink half", "Tiles"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.global), "{names}: {r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {again}"); + } +} + +/// A library tint added with a pattern whose art brought the tint's global color under a numbered +/// name is a tint of that numbered color. +#[test] +fn a_library_tint_follows_the_color_a_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); + assert!(r["added"].as_array().is_some_and(|a| a.contains(&json!("Ink 2"))), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); +} + +/// A numbered copy of a color's name that the library also has as a swatch of its own stands for +/// that swatch alone, even when both library swatches have its color. +#[test] +fn a_numbered_copy_the_library_also_names_is_not_shared() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{r}"); +} + +/// A tint of the document whose global color was deleted without unlinking it is the library's +/// tint only with that color: adding the tint brings the color back under its name, listed as +/// added, and the tint links to it again. +#[test] +fn a_library_tint_whose_color_the_document_deleted_brings_the_color_back() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.delete", json!({"names": ["Ink"], "unlink": false})); + assert!(doc(&s).swatch("Ink").is_none()); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink"]), &json!(["Ink half"])), "{r}"); + assert!(is_global(&s, "Ink", "#0000ff"), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{r}"); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}"); +} + +/// A numbered tint of the document whose global color was deleted without unlinking it is the +/// library's tint only with that color: adding the tint brings the color back under its name. +#[test] +fn a_numbered_tint_whose_color_the_document_deleted_brings_the_color_back() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "color": "#00ff00"})); + run(&mut s, "swatch.new", json!({"name": "Ink half 2", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.delete", json!({"names": ["Ink"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink"]), &json!(["Ink half 2"])), "{r}"); + assert!(is_global(&s, "Ink", "#0000ff"), "{r}"); + assert_eq!(tint_base(&s, "Ink half 2").as_deref(), Some("Ink"), "{r}"); +} + +/// A deleted color that a document tint found here links to keeps its name when the call also +/// picks it, so a pattern added earlier in the call whose art brings another color of a taken +/// name does not take that name first. +#[test] +fn a_deleted_color_a_found_tint_links_to_keeps_its_name_beside_a_pattern() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#00ff00", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 half", "swatch": "Ink 2", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 half", "swatch": "Ink 2", "tint": 50})); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink 2 half", "Ink 2"]})); + assert!(r["existing"].as_array().is_some_and(|a| a.contains(&json!("Ink 2 half"))), "{r}"); + assert_eq!(tint_base(&s, "Ink 2 half").as_deref(), Some("Ink 2"), "{r}"); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}"); + let fill = doc(&s).pattern("Tiles").unwrap().art[0].appearance.fill_paint(); + let Paint::Solid { swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") }; + let green = swatch.clone().unwrap_or_default(); + assert!(is_global(&s, &green, "#00ff00"), "{r}"); +} + +/// A library tint added with a pattern whose art took a numbered copy that the library also names +/// is found again on the next add: the tint links to the copy the art took, and adding the pattern +/// and the tint again adds nothing. +#[test] +fn a_library_tint_linked_to_the_copy_a_pattern_took_is_found_again() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(is_global(&s, &base, "#0000ff"), "{r}"); + // The pattern's art and the tint link to the same color. + let fill = doc(&s).pattern("Tiles").unwrap().art[0].appearance.fill_paint(); + let Paint::Solid { swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") }; + assert_eq!(swatch.as_deref(), Some(base.as_str()), "{r}"); + let swatches = doc(&s).swatches_iter().count(); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); + assert_eq!(again["added"], json!([]), "{again}"); + assert_eq!(doc(&s).swatches_iter().count(), swatches, "{again}"); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{again}"); + assert_eq!(tint_base(&s, "Ink half"), Some(base), "{again}"); +} + +/// Without a pattern whose art takes it, a numbered copy that the library also names stands for +/// that library swatch alone: the document's tint linked to it is not the library's tint of the +/// color the copy is numbered after. +#[test] +fn a_tint_linked_to_a_copy_the_library_names_is_not_another_colors_tint() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink 2", "tint": 50})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(r["existing"], json!([]), "{r}"); + let added = r["added"][0].as_str().unwrap_or_default().to_string(); + let base = tint_base(&s, &added).unwrap_or_default(); + assert!(base != "Ink 2" && is_global(&s, &base, "#0000ff"), "{r}"); +} + +/// A numbered copy of a color's name that the library also has as a swatch of another color is +/// still the copy of the color: adding the color to a document that has such a copy (as a pattern +/// added by an earlier version left it) adds no other copy. +#[test] +fn a_numbered_copy_named_like_another_library_color_is_found() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{r}"); +} + +/// A library tint picked before its global color links to the color under the name it comes in +/// with, not to a numbered copy of the same color when the document has none of the color's name. +#[test] +fn a_library_tint_links_to_its_color_under_the_name_it_comes_in_with() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + for names in [json!(["Ink half", "Ink"]), json!(["Ink", "Ink half"])] { + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{names}: {r}"); + run(&mut s, "swatch.delete", json!({"names": ["Ink half", "Ink"]})); + } +} + +/// A library tint of a spot color links to the spot color a pattern's art brought, not to the +/// document's global process color of the same name and paint. +#[test] +fn a_library_spot_tint_links_to_the_spot_color_not_a_process_one() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + for names in [json!(["Ink", "Tiles", "Ink half"]), json!(["Ink half", "Tiles"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{names}: {r}"); + } +} + +/// The library's process color of a numbered name is not the document's global color of that name +/// and paint, so that global color is the numbered copy of the library's global color it is named +/// after. +#[test] +fn a_numbered_process_color_of_the_library_is_not_the_documents_global_copy() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff"})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 2 2"]), &json!(["Ink 2"])), "{r}"); +} + +/// A library tint added with a pattern whose art took the document's numbered copy of the tint's +/// color is a tint of that copy. +#[test] +fn a_library_tint_follows_the_numbered_color_a_pattern_took() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + for names in [json!(["Tiles", "Ink half"]), json!(["Ink half", "Tiles"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink"), ["Ink 2"], "{names}: {r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{names}: {r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {again}"); + } +} + +/// A numbered copy that the library's own tint of that name is, once its color is linked as the +/// document has it, is not also taken for the library tint it is numbered after. +#[test] +fn a_numbered_tint_the_library_has_is_not_shared() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Half", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.new", json!({"name": "Half 2", "swatch": "Ink", "tint": 50})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Half", "color": "#00ff00"})); + run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Half 2"]})); + assert_eq!(tint_base(&s, "Half 2").as_deref(), Some("Ink 2")); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Half", "Half 2"]})); + assert_eq!(r["existing"], json!(["Half 2"]), "{r}"); + assert_eq!(r["added"].as_array().map(Vec::len), Some(1), "{r}"); +} + +/// The document's swatch `name` is a global color showing `hex`. +fn is_global(s: &Session, name: &str, hex: &str) -> bool { + doc(s).swatch(name).is_some_and(|w| w.global && w.paint.color().is_some_and(|c| c.to_hex() == hex)) +} + +/// A library inks library (global `Ink` #0000ff and its tint `Ink half`) loaded into `s`, which is +/// then left in a new document whose own `Ink` is the same blue as a process color → the id. +fn tinted_ink_library_and_a_process_ink(s: &mut Session) -> Value { + let id = tinted_ink_library_and_a_red_ink(s); + run(s, "swatch.delete", json!({"names": ["Ink"]})); + run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + id +} + +/// A library global color is not the document's process color of the same name and paint: it +/// comes in numbered, its tint links to it, and adding the two again adds nothing. +#[test] +fn a_library_tint_of_a_color_the_document_has_as_process_is_added_once() { + let mut s = session(); + let id = tinted_ink_library_and_a_process_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(base != "Ink" && is_global(&s, &base, "#0000ff"), "{r}"); + let before = (named_after(&s, "Ink"), named_after(&s, "Ink half")); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + assert_eq!(again["added"], json!([]), "{again}"); + assert_eq!((named_after(&s, "Ink"), named_after(&s, "Ink half")), before, "{r} then {again}"); +} + +/// A library tint added without its global color, in a document whose swatch of the color's name +/// is another color or a process color, brings its color along and links to it, not to the +/// document's swatch; adding the tint again adds nothing. +#[test] +fn a_library_tint_added_alone_brings_its_color_beside_a_namesake() { + for process in [false, true] { + let mut s = session(); + let id = if process { tinted_ink_library_and_a_process_ink(&mut s) } else { tinted_ink_library_and_a_red_ink(&mut s) }; + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(base != "Ink" && is_global(&s, &base, "#0000ff"), "process {process}: {r}"); + assert_eq!(r["added"], json!(["Ink half", base]), "process {process}: {r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "process {process}: {again}"); + } +} + +/// A library tint of a spot color is not the document's tint of the same name and paint whose +/// color is a global process color: adding it alone brings the spot color and a tint of it. +#[test] +fn a_library_spot_tint_is_not_the_documents_tint_of_a_process_namesake() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + let tint = r["added"][0].as_str().unwrap_or_default().to_string(); + let base = tint_base(&s, &tint).unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!([tint])), "{again}"); +} + +/// A tint of a process namesake that a pattern's art brings is not taken for a picked library +/// tint of a spot color. +#[test] +fn a_library_spot_tint_is_not_a_process_tint_a_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink half", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let tints: Vec = doc(&s).swatches_iter().filter(|w| w.name.starts_with("Ink half")).map(|w| w.name.clone()).collect(); + if !tints.is_empty() { + run(&mut s, "swatch.delete", json!({"names": tints})); + } + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); + let picked = r["added"].as_array().and_then(|a| a.iter().filter_map(|n| n.as_str()).find(|n| n.starts_with("Ink half"))).unwrap_or_default(); + let base = tint_base(&s, picked).unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}"); +} + +/// A library tint of a spot color added with a pattern whose art the document holds linked to its +/// process color of the spot color's name and paint (as pasting with Merge leaves it) links to a +/// spot color, not to that process color, in either pick order. +#[test] +fn a_library_spot_tint_is_not_linked_to_the_process_color_a_merged_pattern_takes() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + for names in [json!(["Ink half", "Tiles"]), json!(["Tiles", "Ink half"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + // The paste merged the spot color into the document's process color of its name. + assert_eq!(named_after(&s, "Ink"), ["Ink"], "{names}"); + assert!(doc(&s).swatch("Ink").is_some_and(|w| w.global && !w.spot), "{names}"); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{names}: {r}"); + } +} + +/// A color a library pattern's art brings under a numbered name does not take a name the library +/// gives another swatch: adding that swatch next adds it under its own name, and adding the two +/// again adds nothing. +#[test] +fn a_color_a_pattern_brings_skips_the_librarys_numbered_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let brought = + first["added"].as_array().and_then(|a| a.iter().filter_map(|n| n.as_str()).find(|n| n.starts_with("Ink"))).unwrap_or_default().to_string(); + assert!(brought != "Ink 2" && is_global(&s, &brought, "#0000ff"), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{r}"); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink", "Ink 2"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", brought, "Ink 2"])), "{again}"); +} + +/// A pattern whose art brings both a color and the library's numbered color of the same name keeps +/// the numbered color under its own name, and the other color takes the next free one. +#[test] +fn a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone(); + let green = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]})); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [green]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, green]})); + run(&mut s, "select.set", json!({"ids": [blue, green]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{r}"); + assert!(named_after(&s, "Ink").iter().any(|n| n != "Ink" && n != "Ink 2" && is_global(&s, n, "#0000ff")), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink", "Ink 2"]})); + assert_eq!(again["added"], json!([]), "{again}"); +} + +/// A library pattern with a numbered name comes in under that name when the document does not use +/// it. +#[test] +fn a_numbered_library_pattern_keeps_its_name() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert!(r["added"].as_array().is_some_and(|a| a.contains(&json!("Tiles 2"))), "{r}"); + assert!(doc(&s).pattern("Tiles 2").is_some(), "{r}"); +} + +/// A color a library pattern's art brings does not change art of the document that is still +/// linked to a deleted color of a numbered name the library uses. +#[test] +fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#ffff00", "global": true})); + let box_id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [box_id]})); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let fill = doc(&s).node(vectorcraft_doc::NodeId(box_id.as_u64().unwrap())).unwrap().appearance.fill_paint(); + let Paint::Solid { swatch, .. } = &fill else { panic!("the box is filled with a color: {fill:?}") }; + assert_eq!(swatch.as_deref(), Some("Ink 2"), "{r}"); + assert!(doc(&s).swatch("Ink 2").is_none(), "{r}"); +} + +/// A library tint added without its global color to a document that has no swatch of the color's +/// name brings the color along under its own name. +#[test] +fn a_library_tint_added_alone_brings_its_missing_color() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{r}"); + assert!(is_global(&s, "Ink", "#0000ff"), "{r}"); +} + +/// A library tint added with a pattern the document already has (pasted with Merge, so it brings +/// no colors), through the pattern's own swatch or another library swatch of it, is added once, +/// however often the two are added. +#[test] +fn a_library_tint_with_a_pattern_the_document_has_is_added_once() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + s.edit("Dots", |d, _| { + let paint = vectorcraft_doc::pattern::pattern_paint("Squares"); + d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink half"]})); + let before = named_after(&s, "Ink half"); + for pattern in ["Squares", "Dots"] { + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": [pattern, "Ink half"]})); + assert_eq!(named_after(&s, "Ink half"), before, "{pattern}: {first} then {again}"); + } +} + +/// A library gradient whose stops link to a color and to the Registration swatch, picked before or +/// after a pattern whose art brings the color under a numbered name, is not added a second time. +#[test] +fn a_gradient_with_a_registration_stop_before_its_pattern_is_not_copied() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let fade = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "[Registration]"}]}); + run(&mut s, "swatch.new", json!({"name": "Fade", "gradient": fade})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Fade", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + for names in [json!(["Fade", "Squares"]), json!(["Squares", "Fade"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Fade"), ["Fade"], "{names}: {r}"); + } +} + +/// A library tint follows its color when the call picks the color, even when a pattern added +/// before it took the document's numbered copy of that color, with the color itself or with the +/// tint in its art. +#[test] +fn a_library_tint_follows_its_picked_color_not_the_copy_a_pattern_took() { + for tint in [100, 50] { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": tint, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let names = json!(["Tiles", "Ink half", "Ink"]); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + let picked = r["added"].as_array().and_then(|a| a.iter().find(|n| n.as_str().is_some_and(|n| n.starts_with("Ink half"))).cloned()); + let picked = picked.and_then(|n| n.as_str().map(str::to_string)).unwrap_or_default(); + assert_eq!(tint_base(&s, &picked).as_deref(), Some("Ink"), "tint {tint}: {r}"); + let before = named_after(&s, "Ink half"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink half"), before, "tint {tint}: {again}"); + } +} + +/// A library tint is not taken for the tint a pattern brought back in the library color's place +/// when that tint shows the document's own color (the pattern's art links to it, as pasting with +/// Merge leaves it): it comes in as a tint of the library color's numbered copy. +#[test] +fn a_library_tint_is_not_the_one_a_merged_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "the pasted tint follows the document's Ink"); + run(&mut s, "swatch.delete", json!({"names": ["Ink half"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink", "Ink half"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{r}"); + let tint = r["added"][1].as_str().unwrap_or_default().to_string(); + assert!(tint.starts_with("Ink half"), "{r}"); + assert_eq!(tint_base(&s, &tint).as_deref(), Some("Ink 2"), "{r}"); +} + +/// A library gradient is not taken for the gradient a pattern brought back in its place when that +/// gradient's stops show the document's own color. +#[test] +fn a_library_gradient_is_not_the_one_a_merged_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let fade = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}); + run(&mut s, "swatch.new", json!({"name": "Fade", "gradient": fade})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Fade", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + run(&mut s, "swatch.delete", json!({"names": ["Fade"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink", "Fade"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{r}"); + let fade = r["added"][1].as_str().unwrap_or_default().to_string(); + assert!(fade.starts_with("Fade"), "{r}"); + let (first, link) = match doc(&s).swatch(&fade).map(|w| &w.paint) { + Some(Paint::Gradient(g)) => (g.gradient.stops.first().map(|stop| stop.color), g.gradient.stops.first().and_then(|stop| stop.swatch.clone())), + _ => (None, None), + }; + assert_eq!(link.as_deref(), Some("Ink 2"), "the stop links to the library's color: {r}"); + let blue = match doc(&s).swatch("Ink 2").map(|w| &w.paint) { + Some(Paint::Solid { color, .. }) => Some(*color), + _ => None, + }; + assert!(blue.is_some() && first == blue, "{r}"); +} + #[test] fn swatch_exchange_files_load_add_and_list_as_user_libraries() { let bytes = vectorcraft_testkit::ase::sample(); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 8857378855..d49b18b031 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -671,6 +671,48 @@ fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() { s.execute("text.setPathHandle", &handle(Value::Null)).unwrap(); } +/// Range edits, Set Text, area and on-path type and the glyph commands refuse a param of the wrong +/// type with an error naming the param, and leave the document and the undo history as they were: +/// text that is not a string, a byte offset that is fractional or negative, and a point that is not +/// two numbers. Null counts as a param left out, which keeps its default. +#[test] +fn text_edits_refuse_a_param_of_the_wrong_type() { + use crate::tests::not_refused; + let mut s = session(); + let id = text(&mut s, "abc"); + let frame = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 100, "height": 50})).unwrap()["id"].clone(); + let line = s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 400}, {"x": 400, "y": 400}]})).unwrap()["id"].clone(); + let string = |k: &str| format!("`{k}` must be a string"); + let whole = "`start` must be a whole number".to_string(); + let point = "`at` must be a point: [x, y]".to_string(); + let calls: Vec<(String, Value, String)> = [ + ("text.editRange", json!({"id": id.0, "start": 0, "end": 1, "insert": 5}), string("insert")), + ("text.editRange", json!({"id": id.0, "start": 0, "end": 3, "insert": ["x"]}), string("insert")), + ("text.setText", json!({"ids": [id.0], "text": true}), string("text")), + ("text.createInPath", json!({"path": frame, "mode": 1}), string("mode")), + ("text.createInPath", json!({"path": frame, "text": true}), string("text")), + ("text.createInPath", json!({"path": line, "mode": "onPath", "text": "a", "at": [1, "y"]}), point.clone()), + ("text.createInPath", json!({"path": line, "mode": "onPath", "at": [100]}), point.clone()), + ("text.createInPath", json!({"path": frame, "text": "a", "at": "start"}), point), + ("text.touchType", json!({"id": id.0, "start": 1.5, "dy": 2}), whole.clone()), + ("text.touchType", json!({"id": id.0, "start": -1, "dy": 2}), whole.clone()), + ("text.glyphAlternates", json!({"id": id.0, "start": 1.5}), whole.clone()), + ("text.setGlyphAlternate", json!({"id": id.0, "start": -1, "gid": null}), whole), + ] + .into_iter() + .map(|(cmd, p, msg)| (cmd.to_string(), p, msg)) + .collect(); + let wrong = not_refused(&mut s, &calls); + assert!(wrong.is_empty(), "not refused: {wrong:#?}"); + // Null keeps each default: nothing inserted, area type with no text, no start point. + s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 1, "insert": null})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "bc"); + let r = s.execute("text.createInPath", &json!({"path": frame, "mode": null, "text": null, "at": null})).unwrap(); + let t = obj(&s, NodeId(r["id"].as_u64().unwrap())); + assert!(matches!(t.kind, TextKind::Area { .. }) && t.plain_text().is_empty(), "{:?}", t.kind); + s.execute("text.createInPath", &json!({"path": line, "mode": "onPath", "text": "a", "at": [100, 400]})).unwrap(); +} + /// Where each glyph of type object `id` is drawn from (its origin in font units), document space. fn glyph_pens(s: &Session, id: NodeId) -> Vec<(usize, Point)> { let t = obj(s, id); diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index fe3deecbef..39c95da3f6 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -582,6 +582,8 @@ fn colour_table_fixed_palette_keeps_an_opaque_color() { let clear: Vec = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect(); let palette: Vec = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect(); let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}}); + let v = run(&mut d, "document.exportForWeb.preview", p.clone()); + assert_eq!(v["mappedToTransparent"], json!(["#0000ee"]), "the color that did not fit is listed: {v}"); let img = pixels(&one(&mut d, p)); assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0)); // Without transparent pixels the colors mapped to transparent still take one slot together. @@ -598,6 +600,49 @@ fn colour_table_fixed_palette_keeps_an_opaque_color() { assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255])); } +/// With transparent pixels, the colors of a fixed palette mapped to transparent share the +/// transparent pixels' slot, so at 256 colors all 255 opaque colors keep their entries. +#[test] +fn colour_table_fixed_palette_with_transparent_pixels_keeps_255_opaque_colors() { + // A 16×16 grid of 2×2 squares in 255 colors, the last cell left empty (transparent). + let mut s = session(32.0, 32.0); + let color = |i: usize| format!("#{:02x}{:02x}80", i, 255 - i); + for i in 0..255 { + rect(&mut s, [(i % 16) as f64 * 2.0, (i / 16) as f64 * 2.0, 2.0, 2.0], &color(i)); + } + let palette: Vec = (0..255).map(color).chain(["#000000".to_string()]).collect(); + for table in [json!({"customPalette": palette, "transparent": ["#000000"]}), json!({"customPalette": palette[..255], "transparent": []})] { + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": table}); + let img = pixels(&one(&mut s, p.clone())); + let opaque: std::collections::HashSet<[u8; 4]> = img.pixels().map(|p| p.0).filter(|p| p[3] == 255).collect(); + assert_eq!(opaque.len(), 255, "{p}"); + assert_eq!((img.get_pixel(29, 31).0, img.get_pixel(31, 31).0[3]), ([254, 1, 128, 255], 0), "{p}"); + } +} + +/// When Colors leaves a fixed palette fewer slots than it has colors, its locked and shifted colors +/// keep their slots first (shifted ones before locked ones), so a shifted color still shows its new +/// color. +#[test] +fn colour_table_fixed_palette_keeps_locked_and_shifted_colors_first() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#00ff00"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + let palette = json!(["#ff0000", "#00ff00", "#0000ff"]); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": palette, "shifted": {"#0000ff": "#ff8800"}}}); + let img = pixels(&one(&mut s, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0), ([255, 0, 0, 255], [255, 136, 0, 255])); + // A shifted color keeps its slot before the locked ones. + let table = json!({"customPalette": palette, "locked": ["#ff0000", "#00ff00"], "shifted": {"#0000ff": "#ff8800"}}); + let img = pixels(&one(&mut s, json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table}))); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0), ([255, 0, 0, 255], [255, 136, 0, 255])); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": palette, "locked": ["#0000ff"]}}); + let v = run(&mut s, "document.exportForWeb.preview", p); + let sources: Vec<&Value> = v["colors"].as_array().unwrap().iter().map(|c| &c["source"]).collect(); + assert_eq!(sources, vec![&json!("#ff0000"), &json!("#0000ff")], "the palette keeps its order: {v}"); +} + /// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in /// the image, the other colors stay, the table shows it as shifted and locked, and the preview is /// the file. diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index ab823a696e..3c9a7a84cc 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -254,6 +254,170 @@ fn canceling_an_alt_drag_leaves_the_document_as_it_was() { assert!(s.doc().unwrap().interaction.is_none()); } +/// Returns the ids of the children of the document's layer `layer` (0 is the bottom one). +fn layer_kids(s: &Session, layer: usize) -> Vec { + s.doc().unwrap().doc.layers[layer].children().unwrap().iter().map(|n| n.id).collect() +} + +/// Returns a session with three squares side by side, `a`, `b` and `c` from the bottom of the +/// stack up, and `b` selected; and their ids. +fn three_squares() -> (Session, [NodeId; 3]) { + let mut s = session(); + let ids = [100.0, 200.0, 300.0].map(|x| rect(&mut s, x, 100.0, 40.0, 40.0)); + s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap(); + (s, ids) +} + +/// Alt-drags the selection 80 pt down with `tool`, pressing at `press`. +fn alt_drag(s: &mut Session, tool: &str, press: (f64, f64)) { + s.select_tool(tool, ViewInfo::default()).unwrap(); + drag_at(s, PointerKind::Down, press, true); + for dy in [20.0, 50.0, 80.0] { + drag_at(s, PointerKind::Drag, (press.0, press.1 + dy), true); + } + drag_at(s, PointerKind::Up, (press.0, press.1 + 80.0), true); +} + +/// In Draw Behind, an Alt-drag with the Selection tool, or with Direct Selection on an object +/// selected whole, puts the copy directly below its original, selected, in one undo step. In Draw +/// Normal and Draw Inside the copy goes directly above it, as before. +#[test] +fn an_alt_drag_in_draw_behind_puts_the_copy_directly_below_its_original() { + for (tool, press) in [("selection", (220.0, 120.0)), ("directSelection", (200.0, 100.0))] { + for mode in ["behind", "normal", "inside"] { + let (mut s, [a, b, c]) = three_squares(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + alt_drag(&mut s, tool, press); + let what = format!("{tool}, {mode}"); + let kids = layer_kids(&s, 0); + let copy = s.doc().unwrap().selection.objects.clone(); + assert_eq!(copy.len(), 1, "{what}: the copy is selected"); + let want = if mode == "behind" { vec![a, copy[0], b, c] } else { vec![a, b, copy[0], c] }; + assert_eq!(kids, want, "{what}"); + assert!(close(bounds(&s, copy[0]), Rect::new(200.0, 180.0, 240.0, 220.0)), "{what}: {:?}", bounds(&s, copy[0])); + assert!(close(bounds(&s, b), Rect::new(200.0, 100.0, 240.0, 140.0)), "{what}: the original stays"); + assert_eq!(undo_len(&s), undo + 1, "{what}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before, "{what}: Undo gives back the document"); + } + } +} + +/// In Draw Behind, an Alt-drag of several objects puts each copy directly below its own original, +/// in the original's group or layer: objects side by side in one layer, a group (copied whole) and +/// an object in another layer. +#[test] +fn an_alt_drag_in_draw_behind_puts_each_copy_below_its_own_original() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let x = rect(&mut s, 200.0, 100.0, 40.0, 40.0); + let y = rect(&mut s, 260.0, 100.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [x.0, y.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 400.0, 100.0, 40.0, 40.0); + s.execute("layer.new", &json!({})).unwrap(); + let d = rect(&mut s, 500.0, 100.0, 40.0, 40.0); + assert_eq!(layer_kids(&s, 0), vec![a, g, c]); + assert_eq!(layer_kids(&s, 1), vec![d]); + s.execute("select.set", &json!({"ids": [a.0, g.0, c.0, d.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + let undo = undo_len(&s); + alt_drag(&mut s, "selection", (120.0, 120.0)); + let (bottom, top) = (layer_kids(&s, 0), layer_kids(&s, 1)); + assert_eq!(bottom.len(), 6, "{bottom:?}"); + assert_eq!([bottom[1], bottom[3], bottom[5], top[1]], [a, g, c, d], "the originals keep their order"); + let copies = [bottom[0], bottom[2], bottom[4], top[0]]; + let mut selected = s.doc().unwrap().selection.objects.clone(); + selected.sort_unstable(); + let mut want = copies.to_vec(); + want.sort_unstable(); + assert_eq!(selected, want, "the copies are selected"); + let group_copy = s.doc().unwrap().doc.node(copies[1]).unwrap().children().map(Vec::len); + assert_eq!(group_copy, Some(2), "the group is copied whole, once"); + assert_eq!(undo_len(&s), undo + 1); +} + +/// `drawBehind` puts the copies of an interaction's previews below their originals only in Draw +/// Behind and only with `copy`: a later preview without it does not reuse the copies made below, +/// and a transform with `copy` but without `drawBehind`, `object.move` with `copy`, and Transform +/// Again after an Alt-drag in Draw Behind put their copies above. A `drawBehind` that is not true or +/// false is refused, and the document and its undo history stay as they were. +#[test] +fn only_an_alt_drag_copy_follows_draw_behind() { + let (mut s, [a, b, c]) = three_squares(); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + s.begin_interaction("Copy").unwrap(); + let below = json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true}); + s.preview("object.transform", &below).unwrap(); + let first = s.doc().unwrap().selection.objects.clone(); + assert_eq!(layer_kids(&s, 0), vec![a, first[0], b, c]); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 90], "copy": true})).unwrap(); + let second = s.doc().unwrap().selection.objects.clone(); + assert_eq!(layer_kids(&s, 0), vec![a, b, second[0], c], "a copy without `drawBehind` goes above"); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 90], "copy": false, "drawBehind": true})).unwrap(); + assert_eq!(layer_kids(&s, 0), vec![a, b, c], "without `copy`, nothing is copied"); + s.cancel_interaction().unwrap(); + + let (mut s, [a, b, c]) = three_squares(); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + for (cmd, params) in + [("object.transform", json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true})), ("object.move", json!({"dx": 0, "dy": 80, "copy": true}))] + { + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let copy = ids_of(&s.execute(cmd, ¶ms).unwrap()); + assert_eq!(layer_kids(&s, 0), vec![a, b, copy[0], c], "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + // An object listed twice is copied twice, each copy directly below it in turn. + let twice = + ids_of(&s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true, "ids": [b.0, b.0]})).unwrap()); + assert_eq!(layer_kids(&s, 0), vec![a, twice[0], twice[1], b, c]); + s.execute("edit.undo", &json!({})).unwrap(); + + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + alt_drag(&mut s, "selection", (220.0, 120.0)); + let copy = s.doc().unwrap().selection.objects.clone(); + assert_eq!(layer_kids(&s, 0), vec![a, copy[0], b, c]); + let Some(LastTransform::Matrix(_, options)) = s.doc().unwrap().last_transform.clone() else { panic!("the drag is kept for Transform Again") }; + assert!(options.get("drawBehind").is_none(), "{options}"); + let again = ids_of(&s.execute("object.transformAgain", &json!({})).unwrap()); + assert_eq!(layer_kids(&s, 0), vec![a, copy[0], again[0], b, c], "Transform Again copies above"); + + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + let e = s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": "yes"})).unwrap_err(); + assert!(e.to_string().contains("`drawBehind` must be true or false"), "{e}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + assert_eq!(undo_len(&s), undo); +} + +/// In Draw Behind, the copy of a clip group's clipping path goes directly above it, so the clipping +/// path stays the group's bottom child; the copy of the clipped art goes below that art. +#[test] +fn a_copy_in_draw_behind_leaves_the_clipping_path_at_the_bottom() { + let mut s = session(); + let art = rect(&mut s, 100.0, 100.0, 80.0, 80.0); + rect(&mut s, 110.0, 110.0, 40.0, 40.0); + s.execute("select.all", &json!({})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let kids = |s: &Session| -> Vec { s.doc().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect() }; + let [mask, clipped] = kids(&s)[..] else { panic!("{:?}", kids(&s)) }; + assert_eq!(clipped, art); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + let params = |ids: [NodeId; 2]| json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true, "ids": [ids[0].0, ids[1].0]}); + let copies = ids_of(&s.execute("object.transform", ¶ms([mask, art])).unwrap()); + assert_eq!(kids(&s), vec![mask, copies[0], copies[1], art]); + s.execute("edit.undo", &json!({})).unwrap(); + // An object listed twice is copied one at a time, over the clipping path too. + let copies = ids_of(&s.execute("object.transform", ¶ms([mask, mask])).unwrap()); + assert_eq!(kids(&s), vec![mask, copies[1], copies[0], art]); +} + +/// Returns the `ids` of a command's reply. +fn ids_of(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() +} + /// Returns a session with the grid and the square of [`persp_session`], the grid shown with its /// right plane active, and a group of two squares attached to the right plane beside the square, /// with the square and the group selected; and the square's id. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7c1af811ed..f3d615ac8d 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1,7 +1,7 @@ //! Hosting the active tool: pointer/key events → actions → commands. use serde_json::{Map, Value}; -use vectorcraft_doc::Selection; +use vectorcraft_doc::{NodeId, Selection}; use vectorcraft_geom::Point; use vectorcraft_tools::distort::perspective::widget::WidgetPlace; use vectorcraft_tools::draw2::FEEDBACK; @@ -319,6 +319,7 @@ impl Session { /// Pen goes on drawing its path), less the work the gesture ended as a command would: a /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { + let lent_by_bucket = self.lent_by_bucket(); let Some(lender) = self.lender.take() else { return Ok(()) }; // The points the lent tool left picked go back to the tool it was lent to when that tool // picks mesh points, none when it unpicked them all (#8090). Group Selection and the @@ -328,7 +329,12 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|p| lender.options().get("meshPoints") != Some(p)); + // The lent tool's last actions (a drag it cancels or keeps) still count as the Live Paint + // Bucket's when the bucket lent it ([`Session::bucket_paints`]). + let outer_bucket = self.back_to_bucket; + self.back_to_bucket |= lent_by_bucket; let r = self.deactivate_tool(view); + self.back_to_bucket = outer_bucket; self.keep_tool_settings(); self.tool = lender; if let Some(points) = mesh_points { @@ -1548,11 +1554,12 @@ impl Session { } /// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]): - /// the Type tool and the Eyedropper clear a character range whose text is no longer selected. + /// the Type tool and the Eyedropper clear a character range whose text is no longer selected, + /// and the Curvature Circle tool lets the pointer reach its circles once none is selected. /// After `edit.undo` or `edit.redo` (`cmd`), the tool is told first, so the Type tool puts the /// caret where the step changed the text. pub(crate) fn after_command(&mut self, cmd: Option<&str>) { - if self.in_tool_actions || (!self.tool.wants_text() && self.tool.id() != "eyedropper") { + if self.in_tool_actions || (!self.tool.wants_text() && !matches!(self.tool.id(), "eyedropper" | vectorcraft_tools::curvature_circle::ID)) { return; } if let Some(cmd @ ("edit.undo" | "edit.redo")) = cmd { @@ -1754,7 +1761,7 @@ impl Session { (st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields) }; let (overlays, transform_box) = if self.preview(cmd, p).is_ok() { - let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection)).unwrap_or_default(); + let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection, cmd, p)).unwrap_or_default(); let (objects, color) = self .active() .map(|st| (st.selection.objects.clone(), st.selection.objects.first().map(|id| st.doc.layer_color(*id)))) @@ -1795,11 +1802,17 @@ const FEEDBACK_MAX_POINTS: usize = 100_000; /// The outlines of every selected object, a group's members each with their own, or the selection's /// bounds when the outlines' points and the objects evaluated to make them come to more than -/// [`FEEDBACK_MAX_POINTS`]. -fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection) -> Vec { - let nodes = selection.objects.iter().filter_map(|&id| doc.node(id)); - let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS).unwrap_or_else(|| { - doc.bounds_of(&selection.objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect() - }); +/// [`FEEDBACK_MAX_POINTS`]. A `dimension.update` preview (`cmd`, `p`) that names its dimensions, +/// as the Dimension tool sends for a dimension it drags, outlines those dimensions instead. +fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection, cmd: &str, p: &Value) -> Vec { + let named: Vec = if cmd == "dimension.update" { + p.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect() + } else { + vec![] + }; + let objects = if named.is_empty() { &selection.objects } else { &named }; + let nodes = objects.iter().filter_map(|&id| doc.node(id)); + let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS) + .unwrap_or_else(|| doc.bounds_of(objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect()); outlines.into_iter().map(|path| Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: false }).collect() } diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 9c83f697da..b655ed0eb5 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2095,7 +2095,8 @@ 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`.) + /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`, and + /// Invert, Threshold and Posterize layers by `tests_psdlayers::damaged_adjustment_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)) { diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 30f3ce2665..5a6815f298 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -2077,18 +2077,19 @@ fn a_dimension_line_placed_beside_another_lands_on_its_level() { run(&mut s, "object.lock", json!({})); assert_eq!(level_next(&mut s, plain, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5))); // A dimension of the right edge has a vertical line, which is not parallel to the first: the - // pointer 2.5 points below the first line's level places it where the pointer is. + // pointer 2.5 points right of the first line's left end, within reach across the vertical + // line, places it where the pointer is. let (mut s, _) = level_start(plain); linear_click(&mut s, plain, 300.0, 200.0); linear_click(&mut s, plain, 300.0, 300.0); - linear_click(&mut s, plain, 330.0, 172.5); + linear_click(&mut s, plain, 102.5, 172.5); let id = s.doc().unwrap().selection.objects[0].0; - assert_eq!(recipe(&s, id).line_ends(), (pt(330.0, 200.0), pt(330.0, 300.0))); + assert_eq!(recipe(&s, id).line_ends(), (pt(102.5, 200.0), pt(102.5, 300.0))); } /// While a dimension is placed with its line on the level of another, one alignment guide runs -/// along the level across both lines. Off the level, after a dropped press and with Alignment -/// Guides off, no guide shows. +/// along the level across both lines. Off the level, after a dropped press and with Smart Guides +/// or Alignment Guides off, no guide shows. #[test] fn a_dimension_line_on_another_level_shows_one_guide_across_both() { let plain = ViewInfo::default(); @@ -2097,7 +2098,10 @@ fn a_dimension_line_on_another_level_shows_one_guide_across_both() { linear_click(&mut s, plain, 200.0, 200.0); linear_click(&mut s, plain, 300.0, 200.0); let guides = guide_lines(&mut s, plain, 250.0, 172.5); - assert!(guides.iter().any(|(a, b)| near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}"); + assert!(matches!(guides.as_slice(), [(a, b)] if near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}"); + // Smart Guides turned off before the next pointer move: the guide goes. + let off = ViewInfo { smart_guides: false, ..plain }; + assert!(s.overlays(off).iter().all(|o| !matches!(o, vectorcraft_engine::tools::Overlay::Line { .. })), "{:?}", s.overlays(off)); assert!(guide_lines(&mut s, plain, 250.0, 180.0).is_empty(), "no guide off the level"); // A press on the level that the app drops cancels the preview, and its guide goes with it. assert!(!guide_lines(&mut s, plain, 250.0, 172.5).is_empty()); @@ -2115,6 +2119,328 @@ fn a_dimension_line_on_another_level_shows_one_guide_across_both() { assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0))); } +/// A drag with the Dimension tool from a dimension already drawn moves its line as far across as +/// the pointer moved, keeps what it measures and its link to the art, and is one undo step. A +/// click on its line does not move it, and neither does Escape during the drag. +#[test] +fn dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + let (count, label) = (s.doc().unwrap().doc.node_count(), text(&s, first)); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // Dragged up and to the side: the line goes up as far as the pointer, and stays over the + // points it measures. + drag(&mut s, (150.0, 170.0), (180.0, 130.0)); + assert!(!s.in_interaction()); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(100.0, 200.0), pt(200.0, 200.0))); + assert_eq!((s.doc().unwrap().doc.node_count(), text(&s, first)), (count, label)); + // One undo step puts it back. + run(&mut s, "edit.undo", json!({})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + run(&mut s, "edit.redo", json!({})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // Still linked: moving the art moves its points, and the line keeps its distance from them. + let art = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + run(&mut s, "select.set", json!({"ids":[art]})); + run(&mut s, "object.move", json!({"dx":0,"dy":10})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 140.0), pt(200.0, 140.0))); + run(&mut s, "object.move", json!({"dx":0,"dy":-10})); + run(&mut s, "select.none", json!({})); + run(&mut s, "dimension.update", json!({"ids":[first],"at":[150,170]})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // A click on the line picks a point there and leaves the dimension where it is. + linear_click(&mut s, plain, 150.0, 170.0); + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // Escape during the drag leaves it where it was. + ev(&mut s, PointerKind::Down, 150.0, 170.0); + ev(&mut s, PointerKind::Drag, 150.0, 120.0); + assert!(s.in_interaction()); + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + ev(&mut s, PointerKind::Up, 150.0, 120.0); + assert!(!s.in_interaction()); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // A locked dimension is not moved: the drag from its line drags out nothing either. + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "object.lock", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + assert_eq!(s.doc().unwrap().doc.node_count(), count); +} + +/// A dimension moved with the Dimension tool lands on the level of a parallel dimension line +/// within the Smart Guides snapping tolerance, and its own line before the drag is not a level. +#[test] +fn a_dimension_moved_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + linear_click(&mut s, plain, 250.0, 150.0); + let second = s.doc().unwrap().selection.objects[0].0; + run(&mut s, "select.none", json!({})); + assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 150.0), pt(300.0, 150.0))); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // 3.5 points off its own level, with no other level there: where the pointer puts it. + drag(&mut s, (150.0, 170.0), (150.0, 166.5)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 166.5), pt(200.0, 166.5))); + // 2.5 points below the first line's new level: on it. + drag(&mut s, (250.0, 150.0), (250.0, 169.0)); + assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 166.5), pt(300.0, 166.5))); +} + +/// `dimension.update` with `at` puts a linear dimension's line, an angular dimension's arc or a +/// radius line through the point, and keeps what each measures; a bad `at` changes nothing. +#[test] +fn dimension_update_at_moves_the_line_through_the_point() { + let mut s = session(); + let line = edge(&mut s); + let linear = dim(&mut s, line); + let label = text(&s, linear); + run(&mut s, "dimension.update", json!({"ids":[linear],"at":[130,50]})); + let d = recipe(&s, linear); + assert!((d.line_ends().0.y - 50.0).abs() < 1e-9 && (d.line_ends().1.y - 50.0).abs() < 1e-9, "{:?}", d.line_ends()); + assert_eq!(text(&s, linear), label); + let angular = run(&mut s, "dimension.create", json!({"mode":"angular","a":[100,0],"vertex":[0,0],"b":[0,100]}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[angular],"at":[60,0]})); + assert!((recipe(&s, angular).offset - 60.0).abs() < 1e-9); + let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap(); + let radius = run(&mut s, "dimension.create", json!({"mode":"radius","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[radius],"at":[172,400]})); + let d = recipe(&s, radius); + assert!(d.b.distance(vectorcraft_geom::Point::new(172.0, 244.0)) < 1e-6, "turned toward the point: {:?}", d.b); + assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays"); + let before = recipe(&s, linear); + for bad in [json!([1]), json!("x"), json!([0, 1e12])] { + assert!(s.execute("dimension.update", &json!({"ids":[linear],"at":bad})).is_err(), "{bad}"); + assert_eq!(recipe(&s, linear), before); + } +} + +/// A dimension dragged with the Dimension tool follows the part grabbed: a diameter grabbed on its +/// far half turns that half toward the pointer, and an angular arc grabbed away from its middle +/// grows by as much as the pointer moved away from the vertex. +#[test] +fn a_dragged_dimension_follows_the_part_grabbed() { + let plain = ViewInfo::default(); + let mut s = session(); + let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap(); + let diameter = run(&mut s, "dimension.create", json!({"mode":"diameter","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[diameter],"at":[244,172]})); + let angular = + run(&mut s, "dimension.create", json!({"mode":"angular","a":[500,400],"vertex":[400,400],"b":[400,500],"offset":60}))["id"].as_u64().unwrap(); + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", plain).unwrap(); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // Grabbed left of the center and dragged up: the left half goes up, the right half down. + drag(&mut s, (120.0, 172.0), (120.0, 152.0)); + let d = recipe(&s, diameter); + assert!(d.b.y > 172.0 + 1.0, "the half not grabbed turns away from the pointer: {:?}", d.b); + assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays"); + // Grabbed at the center: it turns toward the pointer. + drag(&mut s, (172.0, 172.0), (172.0, 100.0)); + assert!(recipe(&s, diameter).b.distance(vectorcraft_geom::Point::new(172.0, 100.0)) < 1e-6, "{:?}", recipe(&s, diameter).b); + // Grabbed 10° from the arc's start and dragged 20 points straight away from the vertex. + let (sin, cos) = 10f64.to_radians().sin_cos(); + drag(&mut s, (400.0 + 60.0 * cos, 400.0 + 60.0 * sin), (400.0 + 80.0 * cos, 400.0 + 80.0 * sin)); + assert!((recipe(&s, angular).offset - 80.0).abs() < 1e-6, "the arc's radius: {}", recipe(&s, angular).offset); +} + +/// The Dimension tool takes a drag only from a dimension the canvas hits: one painted wider than +/// the reach is taken by its stroke, while one outside isolation mode, around an isolated part of +/// it, clipped away where the press is or drawn elsewhere by a geometry effect stays put. With +/// Real-time Drawing off the dimension being dragged is outlined. +#[test] +fn a_dimension_is_dragged_only_where_the_canvas_hits_it() { + use vectorcraft_engine::tools::Overlay; + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let at_170 = (pt(100.0, 170.0), pt(200.0, 170.0)); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // A 30-point line: a press 13 points from its middle is on its stroke. + let (mut s, first) = level_start(plain); + run(&mut s, "dimension.update", json!({"ids":[first],"options":{"lineWeight":30}})); + drag(&mut s, (115.0, 183.0), (115.0, 143.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // Outside the isolated group: not moved. + let (mut s, first) = level_start(plain); + let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":50,"width":50,"height":50}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[rect]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "object.isolate", json!({"id": group})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // In a clipping mask that leaves its right half out: not taken there, taken on its left half. + let (mut s, first) = level_start(plain); + let mask = run(&mut s, "shape.rectangle", json!({"x":90,"y":140,"width":50,"height":90}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[first, mask]})); + run(&mut s, "object.clippingMask.make", json!({})); + run(&mut s, "select.none", json!({})); + let count = s.doc().unwrap().doc.node_count(); + drag(&mut s, (180.0, 170.0), (180.0, 130.0)); + assert_eq!((recipe(&s, first).line_ends(), s.doc().unwrap().doc.node_count()), (at_170, count)); + // That press picked a point, as a click there does: Escape drops it. + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + drag(&mut s, (120.0, 170.0), (120.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // In a group whose Transform effect draws it 50 points lower: not taken where it is drawn. + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[group],"params":{"moveV":50}})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 220.0), (150.0, 260.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // In Outline view the canvas draws no effects: taken where its recipe puts it. + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + let outline = ViewInfo { outline: true, ..plain }; + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), outline).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // A Transform effect on its parts draws them 50 points lower: not taken where they are drawn. + let (mut s, first) = level_start(plain); + let parts: Vec = s.doc().unwrap().doc.node(NodeId(first)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect(); + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":parts,"params":{"moveV":50}})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 220.0), (150.0, 260.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // With one of its parts isolated, the dimension around it is outside the editing scope. + let (mut s, first) = level_start(plain); + let part = { + let doc = &s.doc().unwrap().doc; + let parts = doc.node(NodeId(first)).unwrap().children().unwrap(); + // The dimension line, which the press below lands on. + let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x0 < 150.0 && r.x1 > 150.0 && r.y0 < 171.0 && r.y1 > 169.0)); + line.unwrap().id.0 + }; + run(&mut s, "object.isolate", json!({"id": part})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // Real-time Drawing off: the dimension is outlined where the drag puts it, and other selected + // art, which the drag does not move, is not. + let (mut s, first) = level_start(plain); + let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":400,"width":50,"height":50}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[first, rect]})); + run(&mut s, "prefs.set", json!({"key": "realTimeDrawing", "value": false})); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 110.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + let boxes: Vec = s + .overlays(plain) + .into_iter() + .filter_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::kurbo::Shape::bounding_box(&path)) } else { None }) + .collect(); + assert!(boxes.iter().any(|r| r.y0 < 111.0 && r.y1 > 109.0 && r.width() >= 99.0), "the dragged dimension is outlined at its new place"); + assert!(!boxes.iter().any(|r| r.x1 > 399.0), "the rectangle is not outlined: {boxes:?}"); +} + +/// A geometry effect on a part of a dimension other than the one pressed keeps the Dimension tool +/// from dragging it, and the effect stays on that part. +#[test] +fn a_geometry_effect_on_another_part_keeps_the_dimension_in_place() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + let extension = { + let doc = &s.doc().unwrap().doc; + let parts = doc.node(NodeId(first)).unwrap().children().unwrap(); + // The extension line at x = 100, which the press below on the dimension line misses. + let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x1 < 101.0 && r.height() > 10.0)); + line.unwrap().id.0 + }; + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[extension],"params":{"moveH":-60}})); + run(&mut s, "select.none", json!({})); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + let kept = s.doc().unwrap().doc.node(NodeId(extension)).is_some_and(|n| !n.appearance.effects.is_empty()); + assert!(kept, "the extension line keeps its effect"); +} + +/// In isolation mode, art outside the isolated group does not take a press on a dimension inside +/// it: the drag moves the dimension. +#[test] +fn art_outside_isolation_does_not_take_the_press_on_a_dimension() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + // A line across the dimension line, outside the group isolated below. The press, a point below + // the dimension line, is nearer to it than to the dimension line. + run(&mut s, "path.create", json!({"d": "M150 100 L150 250"})); + run(&mut s, "select.set", json!({"ids":[first]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "object.isolate", json!({"id": group})); + run(&mut s, "select.none", json!({})); + for (kind, y) in [(PointerKind::Move, 171.0), (PointerKind::Down, 171.0), (PointerKind::Drag, 131.0), (PointerKind::Up, 131.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); +} + +/// A dimension pasted into a document that had none is dragged with the Dimension tool like one +/// drawn there. +#[test] +fn a_dimension_pasted_into_another_document_is_dragged() { + let plain = ViewInfo::default(); + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 612, "height": 792})); + run(&mut s, "edit.paste", json!({})); + let pasted = s.doc().unwrap().selection.objects[0].0; + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", plain).unwrap(); + let (a, b) = recipe(&s, pasted).line_ends(); + let mid = a.midpoint(b); + for (kind, y) in [(PointerKind::Move, mid.y), (PointerKind::Down, mid.y), (PointerKind::Drag, mid.y - 40.0), (PointerKind::Up, mid.y - 40.0)] { + s.pointer(&PointerEvent::new(kind, mid.x, y), plain).unwrap(); + } + let (a2, b2) = recipe(&s, pasted).line_ends(); + assert!((a2.y - (a.y - 40.0)).abs() < 1e-6 && (b2.y - (b.y - 40.0)).abs() < 1e-6, "{:?} → {:?}", (a, b), (a2, b2)); +} + +/// A file that holds a dimension but was saved without the document's dimension flag (as one saved +/// after a dimension was pasted into a document that had none) opens with its dimension dragged +/// by the Dimension tool. +#[test] +fn a_dimension_in_a_file_saved_without_the_flag_is_dragged() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (s, first) = level_start(plain); + let mut doc = s.doc().unwrap().doc.as_ref().clone(); + doc.dimensions = false; + let mut reopened = Session::new(); + reopened.add_document(vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(), None); + reopened.select_tool("dimension", plain).unwrap(); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + reopened.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&reopened, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); +} + /// A second dimension of the same two points as a dimension already drawn lands on its level too. /// Off every level, a pointer moved in small steps while it is placed puts the line at each step, /// with no pull from the preview of the dimension itself. diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index 40752a2fce..be06539537 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -719,7 +719,9 @@ fn alpha_against_supersampled(d: &Document) -> (usize, usize, u8, usize, Vec 10_000, "{name} {of}: {measured} pixels inside"); + // The 3x comparison passes when an opacity is lost or doubled at both scales, so the + // surface's alpha is also checked against the value it should have. + // With 60% gradient stops, each face takes the stops' opacity, so where the front and + // back of the body overlap the alpha is 1 - 0.4 * 0.4 of 255. + let alpha = render(&d).pixel(150, 200)[3]; + let expected = if name.ends_with("fill at 60%") { + 150..=156 + } else if name.ends_with("gradient at 60%") { + 211..=217 + } else { + 255..=255 + }; + if !expected.contains(&alpha) { + failures.push(format!("{name} {of}: surface alpha {alpha}, expected {expected:?}")); + } if off > 0 || past > 0 { failures.push(format!("{name} {of}: of {measured} pixels, {off} off (at most {worst}), {past} past the outline: {first:?}")); } diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 20546835c1..35f29a2a25 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -883,9 +883,10 @@ proptest! { } /// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names, - /// control characters, too long), values, lengths and pointers in and out of its memory runs to - /// an output, never a panic; every call returns a length or a storage code, and the settings and - /// cache of another plug-in in the same store stay as they were. + /// control characters, too long), values, lengths up to about 1 MiB and pointers in and out of + /// its memory runs to an output, or on a small budget to its instruction budget, never a panic; + /// every call returns a length or a storage code, and the settings and cache of another plug-in + /// in the same store stay as they were. #[test] fn hostile_storage_arguments_never_crash( calls in prop::collection::vec( @@ -894,11 +895,12 @@ proptest! { prop_oneof![any::(), 0x1ff00..0x20100i32, Just(0x2000)], prop_oneof![any::(), 0..80i32], prop_oneof![any::(), 0x1ff00..0x20100i32, Just(0x3000)], - prop_oneof![any::(), 0..5000i32], + prop_oneof![any::(), 0..5000i32, 0..1_100_000i32], ), 0..16, ), key in prop::collection::vec(prop_oneof![Just(b'a'), Just(b'.'), Just(b'/'), Just(b'\\'), Just(b'_'), any::()], 0..80), + fuel in prop::option::of(1_000..200_000u64), ) { use vectorcraft_plugins::host::STORAGE_BUDGET; use vectorcraft_plugins::storage::Meter; @@ -936,17 +938,31 @@ proptest! { .collect(); let text: String = key.iter().map(|b| format!("\\{b:02x}")).collect(); let imports = format!(r#"{} (data (i32.const 0x2000) "{text}")"#, tpl::STORAGE_IMPORTS); - let wasm = wat::parse_str(tpl::with_imports(&storing("fuzz.storage"), &imports, &format!("(local $r i32) {body}"), r#"{"objects":[]}"#)).unwrap(); + // 64 more pages hold the values of the large writes. + let wasm = wat::parse_str(tpl::with_imports( + &storing("fuzz.storage"), + &imports, + &format!("(local $r i32) (drop (memory.grow (i32.const 64))) {body}"), + r#"{"objects":[]}"#, + )) + .unwrap(); // A failed case leaves its module installed, and the cases that shrink it install others // under the same id. let r = catch_quiet(|| { s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})) .map_err(|e| e.to_string())?; let p = vectorcraft_plugins::registry::get("fuzz.storage").ok_or("not installed")?; - p.run(b"{\"objects\":[]}", b"{}").map_err(|e| e.to_string()) + // A small budget runs out on the bytes the storage calls move. + let limits = Limits { fuel_base: fuel.unwrap_or(p.limits().fuel_base), fuel_per_byte: 0, ..p.limits().clone() }; + p.run_limited(b"{\"objects\":[]}", b"{}", &limits).map_err(|e| e.to_string()) }); let out = r.map_err(|msg| TestCaseError::fail(format!("panicked on {calls:?}: {msg}")))?; - prop_assert!(out.is_ok(), "{:?}", out); + prop_assert!( + out.is_ok() || (fuel.is_some() && out == Err(Error::Limit("instruction budget".into()).to_string())), + "{:?} on {:?} instructions", + out, + fuel + ); prop_assert_eq!(theirs.setting("mine", m).unwrap(), Some(b"kept".to_vec())); prop_assert_eq!(theirs.cache_entry("mine", m).unwrap(), Some(b"kept".to_vec())); prop_assert_eq!(theirs.cache_bytes(), 4); diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index a469e68f20..6cb261dd0f 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -506,6 +506,134 @@ fn expand_appearance_in_safe_mode_checks_symbol_art_a_group_image_draws() { refused(&mut s, &json!(outer)); } +/// In Safe Mode, a hidden plain instance draws nothing in the image a group's raster effect makes, +/// so its symbol art's plug-in effect doesn't stop Expand Appearance of the group; shown, it does. +#[test] +fn expand_appearance_in_safe_mode_skips_symbol_art_of_a_hidden_instance_a_group_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.hid", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.hid"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let hide = |s: &mut Session, id: u64| { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(vectorcraft_engine::doc::NodeId(id)).unwrap().visible = false; + }; + let expand = |s: &mut Session, group: u64| { + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({"ids": [group]})); + safe_mode::set_active(None); + r + }; + // A blurred group of a visible rectangle and an instance, then one of a visible rectangle and a + // group around an instance; the instance, or the group around it, is shown and then hidden. + for wrap in [false, true] { + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone(); + let mut hidden = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone(); + if wrap { + hidden = s.execute("object.group", &json!({"ids": [hidden]})).unwrap()["id"].clone(); + } + let group = s.execute("object.group", &json!({"ids": [rect, hidden]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap(); + let (hidden, group) = (hidden.as_u64().unwrap(), group.as_u64().unwrap()); + let err = expand(&mut s, group).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + hide(&mut s, hidden); + expand(&mut s, group).unwrap(); + } + // Expansion still makes the image of a hidden blurred group, or of one in a hidden group, so + // a shown instance in it still stops it. + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 20})).unwrap()["id"].clone(); + let blurred = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [blurred], "params": {"radius": 2}})).unwrap(); + let parent = s.execute("object.group", &json!({"ids": [blurred]})).unwrap()["id"].as_u64().unwrap(); + hide(&mut s, parent); + let err = expand(&mut s, parent).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + let blurred = blurred.as_u64().unwrap(); + hide(&mut s, blurred); + let err = expand(&mut s, blurred).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); +} + +/// In Safe Mode, the image a layer's raster effect makes leaves out a template sublayer, so the symbol +/// art of a plain instance in it doesn't stop Expand Appearance of the layer; in a plain sublayer, it does. +#[test] +fn expand_appearance_in_safe_mode_skips_symbol_art_in_a_template_sublayer_a_layer_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.tpl", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.tpl"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setCurrent", &json!({"id": layer})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap(); + let instance = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].as_u64().unwrap(); + let sub = s.execute("layer.newSublayer", &json!({"parent": layer})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.move", &json!({"ids": [instance], "target": sub})).unwrap(); + s.execute("layer.target", &json!({"id": layer})).unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [layer], "item": null, "params": {"radius": 2}})).unwrap(); + let blurred = |s: &Session| s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(layer)).unwrap().appearance.effects.len(); + assert_eq!(blurred(&s), 1, "the layer has its own Gaussian Blur"); + let expand = |s: &mut Session| { + s.execute("layer.target", &json!({"id": layer})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({})); + safe_mode::set_active(None); + r + }; + let err = expand(&mut s).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + s.execute("layer.setProps", &json!({"id": sub, "template": true})).unwrap(); + expand(&mut s).unwrap(); +} + +/// In Safe Mode, a group whose Gaussian Blur makes it one image leaves out a hidden blurred group in +/// it, which makes no image of its own, so the symbol art of a plain instance there doesn't stop +/// Expand Appearance. Under a Drop Shadow, whose members expand on their own, the hidden group still +/// makes its image, so it does. +#[test] +fn expand_appearance_in_safe_mode_skips_a_hidden_blurred_group_that_a_blurred_group_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.nest", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.nest"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let expand = |s: &mut Session, group: u64| { + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({"ids": [group]})); + safe_mode::set_active(None); + r + }; + for (outer, allowed) in [("blur.gaussian", true), ("stylize.dropShadow", false)] { + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone(); + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone(); + let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [inner], "params": {"radius": 2}})).unwrap(); + let group = s.execute("object.group", &json!({"ids": [rect, inner]})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": outer, "ids": [group]})).unwrap(); + let inner = vectorcraft_engine::doc::NodeId(inner.as_u64().unwrap()); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(inner).unwrap().visible = false; + let r = expand(&mut s, group); + if allowed { + r.unwrap(); + // The blurred group became its image: the hidden group in it was not expanded on its own. + assert!(s.doc().unwrap().doc.node(inner).is_none(), "the hidden group went into the image"); + } else { + let err = r.unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{outer}: {err}"); + } + } +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] diff --git a/crates/eps/src/print/tests.rs b/crates/eps/src/print/tests.rs index 4c922b25e9..7600435c79 100644 --- a/crates/eps/src/print/tests.rs +++ b/crates/eps/src/print/tests.rs @@ -403,3 +403,16 @@ fn overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below ]; assert_keeps_the_ink_below(&cases); } + +#[test] +fn an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_without_ink_on_a_postscript_plate() { + // 0.1% cyan around the left point: not paper white, but the plate's 8-bit samples write it as + // none of the ink, so the cyan below prints there. + let (faint, inked) = (Color::cmyk(0.001, 0.3, 0.0, 0.0), Color::cmyk(0.6, 0.3, 0.0, 0.0)); + let mut freeform = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, faint), GradientStop::new(1.0, inked)])); + let pure = |at: Point, c: Color| FreeformPoint { spread: 0.9, ..FreeformPoint::new(at, c) }; + freeform.freeform = + Some(Freeform { points: vec![pure(Point::new(50.0, 50.0), faint), pure(Point::new(150.0, 50.0), inked)], ..Default::default() }); + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + assert_keeps_the_ink_below(&[("faint", overprinting(Paint::Gradient(Box::new(freeform)), Paint::None), cyan, "Cyan")]); +} diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index be26ba8c4f..35a68371b1 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -8,7 +8,6 @@ use std::sync::Arc; use kurbo::Shape; use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint}; -use vectorcraft_doc::overprint::is_white; use vectorcraft_doc::{ AppearanceItem, ColorMode, Document, Effect, ImageBlob, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, SymbolBoxes, TextObject, }; @@ -1586,30 +1585,61 @@ impl<'a> Scene<'a> { let field = g.freeform_on(b).model_field(spread_scale(b)); let q = |v: f32| (unit(v) * 255.0).round() as u8; let (w, h) = (u32::from(cols), u32::from(rows)); - // Overprinting on a plate: the cells of paper white put none of the ink down, so they are - // left out, as clear pixels at Level 3 and outside a clip of the other cells at Level 2. - let blank: Option> = self.keep_below.then(|| field.grid(area, cols, rows).map(|(c, _)| is_white(&Paint::solid(c))).collect()); + let in_inks = field.model() == Some(Model::Cmyk) || (self.cmyk && field.model() == Some(Model::Gray)); + // Each cell's samples: its inks or its RGB, then its alpha. + let (mut samples, paper): (Vec, u8) = if in_inks { + let inks = field.grid(area, cols, rows).flat_map(|(color, a)| { + let [c, m, y, k] = color.to_cmyk(); + [q(c), q(m), q(y), q(k), q(a)] + }); + (inks.collect(), 0) + } else { + (field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect(), 255) + }; + let n = if in_inks { 5 } else { 4 }; + // Overprinting on a plate: the cells whose samples put none of the ink down once their + // opacity is applied, as `encode_inks` and `encode_image` write them (RGB converted to + // CMYK in CMYK output), are left out, as clear pixels at Level 3 and outside a clip of the + // other cells at Level 2. + let written = |v: u8, a: u8| { + let (v, a) = (u32::from(v), u32::from(a)); + ((v * a + u32::from(paper) * (255 - a) + 127) / 255) as u8 + }; + let (cms, to_cmyk) = (self.cms.clone(), !in_inks && self.cmyk); + let intent = cms.settings().intent; + let mut converted: HashMap<[u8; 3], bool> = HashMap::new(); + let blank: Option> = self.keep_below.then(|| { + samples + .chunks(n) + .map(|s| { + let a = s.last().copied().unwrap_or(0); + if a == 0 || in_inks { + return s.iter().take(n - 1).all(|&v| written(v, a) == paper); + } + let rgb = [0, 1, 2].map(|i| s.get(i).map_or(paper, |&v| written(v, a))); + if !to_cmyk { + return rgb == [paper; 3]; + } + *converted.entry(rgb).or_insert_with(|| { + let inks = cms.srgb_to_cmyk(rgb.map(|x| f32::from(x) / 255.0), intent); + inks.iter().all(|&x| (unit(x) * 255.0).round() as u8 == 0) + }) + }) + .collect() + }); let blank = blank.filter(|b| b.contains(&true)); if blank.as_ref().is_some_and(|b| !b.contains(&false)) { return; } let keyed = self.o.level == Level::Three; - let clear = |i: usize, a: u8| if keyed && blank.as_ref().is_some_and(|b| b[i]) { 0 } else { a }; - let image = if field.model() == Some(Model::Cmyk) || (self.cmyk && field.model() == Some(Model::Gray)) { - let inks: Vec = field - .grid(area, cols, rows) - .enumerate() - .flat_map(|(i, (color, a))| { - let [c, m, y, k] = color.to_cmyk(); - [q(c), q(m), q(y), q(k), clear(i, q(a))] - }) - .collect(); - self.encode_inks(&inks, w, h) - } else { - let rgba: Vec = - field.display_grid(area, cols, rows).enumerate().flat_map(|(i, (c, a))| [q(c[0]), q(c[1]), q(c[2]), clear(i, q(a))]).collect(); - self.encode_image(&rgba, w, h) - }; + if let Some(b) = blank.as_ref().filter(|_| keyed) { + for (s, _) in samples.chunks_mut(n).zip(b).filter(|(_, blank)| **blank) { + if let Some(a) = s.last_mut() { + *a = 0; + } + } + } + let image = if in_inks { self.encode_inks(&samples, w, h) } else { self.encode_image(&samples, w, h) }; let Some(image) = image else { return }; let cells = blank.filter(|_| !keyed).map(|b| { let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows)); @@ -1631,8 +1661,13 @@ impl<'a> Scene<'a> { bp }); if let Some(bp) = &cells { - // Each row's run of cells is a rectangle of five path elements, about 60 bytes. - if self.size().saturating_add(bp.elements().len().saturating_mul(12)).saturating_add(image.inline_len) > self.max_body { + // Each row's run of cells is a rectangle of five path elements, about 60 bytes. The + // image is a reference when one encoded the same is already drawn. + let cost = self + .kept_field(&image) + .and_then(|i| self.codes.get(i)) + .map_or(image.inline_len, |c| if c.uses == 0 { c.inline_len } else { c.ref_len }); + if self.size().saturating_add(bp.elements().len().saturating_mul(12)).saturating_add(cost) > self.max_body { self.warn(TOO_LARGE); return; } @@ -1649,9 +1684,7 @@ impl<'a> Scene<'a> { /// image already kept when one is encoded the same. fn place_field(&mut self, image: ImageCode, place: Affine) { let key = image.content_key(); - let found = - self.fields.get(&key).and_then(|bucket| bucket.iter().copied().find(|&i| self.codes.get(i).is_some_and(|c| c.same_image(&image)))); - let i = match found { + let i = match self.kept_field(&image) { Some(i) => i, None => { // A field that can't be placed isn't kept. @@ -1667,6 +1700,12 @@ impl<'a> Scene<'a> { self.place_image(i, place); } + /// The index in `codes` of a kept freeform gradient image encoded the same as `image`. + fn kept_field(&self, image: &ImageCode) -> Option { + let bucket = self.fields.get(&image.content_key())?; + bucket.iter().copied().find(|&i| self.codes.get(i).is_some_and(|c| c.same_image(image))) + } + /// Forget the encoded images after the first `n` codes that no placement draws any longer, and /// the cache entries that name them: placed images, colorized images and fields. A code that a /// placement still draws keeps itself and every code before it. diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index cf62695254..e6161da23d 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1605,6 +1605,62 @@ fn a_field_taken_back_at_the_page_limit_leaves_no_image_behind() { assert!(page.setup.contains("/VCim0 VCsrc") && !page.setup.contains("VCim1"), "{}", page.setup); } +/// On a plate at Level 2, an overprinting field drawn again inside the clip of its inked cells +/// is charged the reference to the image already kept against the page limit, not its samples a +/// second time: a page with room for that reference keeps both placements. +#[test] +fn a_repeated_field_clipped_on_a_plate_is_charged_its_reference_at_the_page_limit() { + let square = |d: &mut Document| { + // Wide spreads of pure color: paper white around the left point. + let mut g = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Default::default() }); + let pure = |x: f64, c: Color| FreeformPoint { spread: 0.9, ..FreeformPoint::new(Point::new(x, 32.0), c) }; + g.freeform = Some(Freeform { points: vec![pure(12.0, Color::gray(0.0)), pure(52.0, Color::gray(0.6))], ..Default::default() }); + let mut n = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 64.0, 64.0)), Paint::Gradient(Box::new(g)), Paint::None, 0.0); + for it in &mut n.appearance.items { + *it.overprint_mut() = true; + } + n + }; + let twice = doc_with(|d| vec![square(d), square(d)]); + let o = EpsOptions { level: Level::Two, ..opts(&twice) }; + let full = crate::scene::Scene::new(&twice, &o).on_plate(true).run(); + assert!(full.warnings.is_empty(), "{:?}", full.warnings); + assert_eq!(reuses(&full.body, 0, Level::Two), 2, "{}", full.body); + assert!(full.body.contains("\nW\n"), "the inked cells clip the image: {}", full.body); + // The image's samples are in the setup and the body draws them twice. The limit leaves room + // for the body and the samples twice over (the clip is charged more than it writes), though + // not for the samples charged again at the second placement. + assert!(full.setup.len() > 2_000, "{}", full.setup.len()); + let limit = full.body.len() + 2 * full.setup.len(); + let page = crate::scene::Scene::new(&twice, &o).on_plate(true).with_max_body(limit).run(); + assert!(page.warnings.is_empty(), "{:?}", page.warnings); + assert_eq!((&page.setup, &page.body), (&full.setup, &full.body)); +} + +/// On a plate, an overprinting freeform gradient whose cells are translucent enough that their +/// opacity takes every sample to no ink (or to paper white in RGB) draws no image at either level. +#[test] +fn a_translucent_field_whose_samples_write_no_ink_on_a_plate_draws_no_image() { + let faint = [Color::cmyk(0.004, 0.0, 0.0, 0.0), Color::rgb(254.0 / 255.0, 254.0 / 255.0, 254.0 / 255.0)]; + for color in faint { + let d = doc_with(|d| { + let mut g = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Default::default() }); + let point = |x: f64| FreeformPoint { opacity: 0.25, ..FreeformPoint::new(Point::new(x, 32.0), color) }; + g.freeform = Some(Freeform { points: vec![point(12.0), point(52.0)], ..Default::default() }); + let mut n = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 64.0, 64.0)), Paint::Gradient(Box::new(g)), Paint::None, 0.0); + for it in &mut n.appearance.items { + *it.overprint_mut() = true; + } + vec![n] + }); + for level in [Level::Three, Level::Two] { + let o = EpsOptions { level, ..opts(&d) }; + let out = crate::scene::Scene::new(&d, &o).on_plate(true).run(); + assert!(!out.body.contains("image"), "{color:?} at {level:?}: {}", out.body); + } + } +} + /// A 200 × 200 pt document holding 8 × 8 pixels of noise as image `pic` and a three-pixel gray ramp /// as image `gray`, its first layer holding what `nodes` makes. fn image_doc_with(nodes: impl FnOnce(&mut Document) -> Vec) -> Document { diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index a8c7358aa7..430769069d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -637,6 +637,11 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize // Untrusted: the type's sizes, leading, baseline shifts and scales, its indents and paragraph // spacing, and its tab stops, each within its range (after the depth limit: the walk recurses). doc.keep_type_values_in_range(); + // Untrusted, and unset in a file saved after a dimension was pasted into a document that had + // none: the flag is set when some object is a dimension (after the depth limit too). + let mut dimensions = false; + doc.walk(|n| dimensions |= n.extras().dimension.is_some()); + doc.dimensions = dimensions; // Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too). doc.fix_ruby(); // Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite). diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index c962bf9679..30de04cf12 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -443,19 +443,32 @@ fn path_call(i: &mut Interp, this: &Value, what: &str, name: &str, args: &[Value Ok(Value::Bool(outcome(i, o, &r)?)) } -/// `createAlias`: not available, so it sets `error` and returns `false`. -fn create_alias(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - let (o, _) = this_path(i, &this, "createAlias")?; - let m = message(i, "noAlias")?; - set_slot(i, o, ERROR, m)?; - Ok(Value::Bool(false)) +/// `createAlias(target)`: an alias at the object's path that leads to `target`, a path or a `File`. +/// Without a target the host gets an empty path, which names no file. +fn create_alias(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "createAlias")?; + let fs = match arg(args, 0) { + Value::Undefined | Value::Null => Value::str(""), + target => { + let p = parse(i, &target)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))? + } + }; + i.rooted(std::slice::from_ref(&fs), |i| path_call(i, &this, "createAlias", "createAlias", std::slice::from_ref(&fs))) } -/// Setting `hidden`: not available, so it sets `error` and changes nothing. -fn set_hidden(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - let (o, _) = this_path(i, &this, "hidden")?; - let m = message(i, "noHidden")?; - set_slot(i, o, ERROR, m)?; +/// Setting `hidden`: the host may give the file a new path, which the object then takes. A file +/// the object has open stays open, at the new path. +fn set_hidden(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "hidden")?; + let on = Value::Bool(arg(args, 0).truthy()); + let r = i.rooted(std::slice::from_ref(&path), |i| host(i, "setHidden", &[path.clone(), on]))?; + if outcome(i, o, &r)? { + let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; + if matches!(fs, Value::String(_)) { + set_slot(i, o, PATH, fs)?; + } + } Ok(Value::Undefined) } @@ -1173,7 +1186,7 @@ mod tests { ("parent", Data::String("/".into())), ]) }; - let messages = ["notOpen", "badMode", "noAlias", "noHidden"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); + let messages = ["notOpen", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); let stat = move |a: Vec| -> Result { let dir = text(&a, 0) == "/d"; Ok(obj(vec![("exists", Data::Bool(dir)), ("dir", Data::Bool(dir))])) diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d675e82ec7..ee2cd364f8 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -491,10 +491,10 @@ impl Realm { /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, - /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `pick` (the file - /// dialogs, where a run may wait), `encode`, `decode`, `encodingAvailable`, `current` and - /// `locations`, with the values `system` and `lineFeed` and the messages `text.notOpen`, - /// `text.badMode`, `text.noAlias` and `text.noHidden`. Each object keeps its path, its `error` + /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `setHidden`, + /// `createAlias`, `pick` (the file dialogs, where a run may wait), `encode`, `decode`, + /// `encodingAvailable`, `current` and `locations`, with the values `system` and `lineFeed` and + /// the messages `text.notOpen` and `text.badMode`. Each object keeps its path, its `error` /// text, its open file's id, its encoding and its line feed in properties that are not /// enumerable. pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index bf32bcfcd6..23337128bb 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -27,6 +27,17 @@ //! an ES5 section apart from the other tests without a feature tag; its failures go to //! `builtins-failures.txt`. The interpreter tests fail when the interpreter panics, when a harness //! or test file cannot be read, or when no ES5 test runs. +//! +//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every +//! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset +//! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the +//! folders [`ANNEX_B_BUILT_INS`] names through the interpreter (failures in +//! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without +//! `test/annexB/` skips them; a folder there with no test to parse or run fails them. +//! +//! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses +//! an `includes:` name that leaves the `harness/` folder, and refuses a file over +//! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -56,23 +67,100 @@ fn suite_dir() -> Option { dirs.pop() } -/// The `.js` files under `dir`, sorted, with the `_FIXTURE` helper files left out. -fn test_files(dir: &Path) -> Vec { +/// The largest test or harness file read (the largest file in the pinned suite is 3,234,014 bytes). +const MAX_FILE_BYTES: u64 = 8 << 20; + +/// The value of `result`; an error fails the test with its message. +fn or_fail(result: Result) -> T { + assert!(result.is_ok(), "{}", result.as_ref().err().map_or("", String::as_str)); + result.unwrap_or_default() +} + +/// `dir` joined with the `/`-separated path `rel`. An empty, `.` or `..` component, one holding a +/// `\` or `:`, and a component that is a symbolic link give an error, so the path stays inside +/// `dir`. A component that does not exist is not checked further. +fn inside(dir: &Path, rel: &str) -> Result { + let mut path = dir.to_path_buf(); + for part in rel.split('/') { + if part.is_empty() || part == "." || part == ".." || part.contains(['\\', ':']) { + return Err(format!("{rel} is not a path inside {}", dir.display())); + } + path.push(part); + if std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(format!("{} is a symbolic link; the runner reads only files inside the suite", path.display())); + } + } + Ok(path) +} + +/// `dir` joined with `rel` as [`inside`] gives it, or `None` when nothing is at that path. A path +/// whose metadata cannot be read, such as one under a folder that cannot be searched, gives an error. +fn present(dir: &Path, rel: &str) -> Result, String> { + let path = inside(dir, rel)?; + match path.try_exists() { + Ok(true) => Ok(Some(path)), + Ok(false) => Ok(None), + Err(e) => Err(format!("cannot read {}: {e}", path.display())), + } +} + +/// Reads a test or harness file: a regular file (not a symbolic link) of at most +/// [`MAX_FILE_BYTES`], with invalid UTF-8 replaced. +fn read_source(path: &Path) -> Result { + let meta = std::fs::symlink_metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if !meta.is_file() { + return Err(format!("{} is not a regular file", path.display())); + } + if meta.len() > MAX_FILE_BYTES { + return Err(format!("{} is {} bytes, over the {MAX_FILE_BYTES}-byte limit", path.display(), meta.len())); + } + let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + +/// The `.js` files under `dir`, sorted, with the `_FIXTURE` helper files and symbolic links left +/// out. A folder or entry that cannot be read gives an error. +fn test_files(dir: &Path) -> Result, String> { let mut out = Vec::new(); let mut stack = vec![dir.to_path_buf()]; while let Some(d) = stack.pop() { - let Ok(entries) = std::fs::read_dir(&d) else { continue }; - for entry in entries.flatten() { + let entries = std::fs::read_dir(&d).map_err(|e| format!("cannot read {}: {e}", d.display()))?; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot read {}: {e}", d.display()))?; let path = entry.path(); - if path.is_dir() { + let kind = entry.file_type().map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if kind.is_dir() { stack.push(path); - } else if path.extension().is_some_and(|e| e == "js") && !path.to_string_lossy().contains("_FIXTURE") { + } else if kind.is_file() && path.extension().is_some_and(|e| e == "js") && !path.to_string_lossy().contains("_FIXTURE") { out.push(path); } } } out.sort(); - out + Ok(out) +} + +/// The modes a test runs in, `true` for strict mode code: both, unless its `onlyStrict`, +/// `noStrict` or `raw` flag says otherwise. +fn modes(meta: &Meta) -> &'static [bool] { + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if has("raw") || has("noStrict") { + &[false] + } else if has("onlyStrict") { + &[true] + } else { + &[false, true] + } +} + +/// The test is a script without a feature tag and, unless `any_edition` is set, names an ES5 +/// section. The Annex B tests name the edition they were written for with `esid:`, so they are +/// read with `any_edition`. +fn eligible(meta: &Meta, any_edition: bool) -> bool { + (meta.es5 || any_edition) + && meta.features.is_empty() + && !meta.flags.iter().any(|f| f == "module") + && meta.negative_phase.as_deref() != Some("resolution") } /// A YAML flow list (`[a, b]`) or the block list (`- a` lines) after a key. @@ -127,70 +215,15 @@ fn es5_parse_subset() { println!("test262: SKIPPED (no suite; run cargo xtask test262)"); return; }; - let language = dir.join("test").join("language"); + let language = or_fail(inside(&dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); - let files = test_files(&language); + let files = or_fail(test_files(&language)); assert!(!files.is_empty(), "no tests under {}", language.display()); - // VECTORCRAFT_TEST262_VERBOSE=1 prints each test before it is parsed. - let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); - - let (mut positive, mut negative, mut with_features, mut modules) = (0usize, 0usize, 0usize, 0usize); - let (mut passed, mut failed) = (0usize, 0usize); - // The tests without a feature tag that name no ES5 section: files, runs passed and failed. - let (mut later, mut later_passed, mut later_failed) = (0usize, 0usize, 0usize); - let mut failures = String::new(); - let mut later_failures = String::new(); - for path in &files { - let source = String::from_utf8_lossy(&std::fs::read(path).unwrap()).into_owned(); - let meta = meta(&source); - if !meta.features.is_empty() { - with_features += 1; - continue; - } - if meta.flags.iter().any(|f| f == "module") || meta.negative_phase.as_deref() == Some("resolution") { - modules += 1; - continue; - } - let expect_error = meta.negative_phase.as_deref() == Some("parse"); - if !meta.es5 { - later += 1; - } else if expect_error { - negative += 1; - } else { - positive += 1; - } - let has = |flag: &str| meta.flags.iter().any(|f| f == flag); - let modes: &[bool] = if has("raw") || has("noStrict") { - &[false] - } else if has("onlyStrict") { - &[true] - } else { - &[false, true] - }; - for &strict in modes { - if verbose { - eprintln!("{} ({})", path.display(), if strict { "strict" } else { "sloppy" }); - } - let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() }; - let result = parse(&text, &Options::default()); - let (pass, fail, list) = - if meta.es5 { (&mut passed, &mut failed, &mut failures) } else { (&mut later_passed, &mut later_failed, &mut later_failures) }; - if result.is_err() == expect_error { - *pass += 1; - } else { - *fail += 1; - let rel = path.strip_prefix(&dir).unwrap_or(path).display().to_string().replace('\\', "/"); - let mode = if strict { "strict" } else { "sloppy" }; - let outcome = match &result { - Ok(_) => "parsed; a SyntaxError was expected".to_string(), - Err(e) => e.to_string(), - }; - list.push_str(&format!("{rel} ({mode}): {outcome}\n")); - } - } - } + let ParseRun { main: es5, later: other, with_features, modules } = or_fail(parse_files(&dir, &files, false)); + let (positive, negative, passed, failed) = (es5.positive, es5.negative, es5.passed, es5.failed); + let (later, later_passed, later_failed) = (other.positive + other.negative, other.passed, other.failed); let report = dir.join("failures.txt"); - std::fs::write(&report, format!("# ES5 subset\n{failures}\n# Other tests without a feature tag\n{later_failures}")).unwrap(); + std::fs::write(&report, format!("# ES5 subset\n{}\n# Other tests without a feature tag\n{}", es5.failures, other.failures)).unwrap(); println!( "test262 ES5 parse subset ({}): {} tests ({positive} that must parse, {negative} that must give a SyntaxError), \ {passed} runs passed, {failed} failed. Other tests without a feature tag: {later} tests, {later_passed} runs passed, \ @@ -201,6 +234,119 @@ fn es5_parse_subset() { ); } +#[test] +fn annex_b_parse_subset() { + let Some(dir) = suite_dir() else { + println!("test262 Annex B parse: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + parse_annex_b(&dir); +} + +/// Parses the tests without a feature tag under `test/annexB/language`, of any edition, prints the +/// counts and writes the failures to `annexb-parse-failures.txt` beside the suite. +fn parse_annex_b(dir: &Path) { + if or_fail(present(dir, "test/annexB")).is_none() { + println!("test262 Annex B parse: SKIPPED ({} has no test/annexB)", dir.display()); + return; + } + // A suite with `test/annexB` and no `test/annexB/language` fails in the walk. + let language = or_fail(inside(dir, "test/annexB/language")); + let files = or_fail(test_files(&language)); + let ParseRun { main, with_features, modules, .. } = or_fail(parse_files(dir, &files, true)); + assert!(main.positive + main.negative > 0, "no Annex B tests to parse under {}", language.display()); + let report = dir.join("annexb-parse-failures.txt"); + if let Err(e) = std::fs::write(&report, &main.failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 Annex B language parse: {} tests ({} that must parse, {} that must give a SyntaxError), {} runs passed, {} failed. \ + Skipped {with_features} tests with feature tags and {modules} module tests. Failures: {}", + main.positive + main.negative, + main.positive, + main.negative, + main.passed, + main.failed, + report.display() + ); +} + +/// The parse counts of one group of tests. +#[derive(Default)] +struct ParseCounts { + /// Tests that must parse. + positive: usize, + /// Tests that must give a `SyntaxError`. + negative: usize, + passed: usize, + failed: usize, + failures: String, +} + +/// The counts of [`parse_files`]. +#[derive(Default)] +struct ParseRun { + /// The tests that name an ES5 section, or every eligible test when any edition is read. + main: ParseCounts, + /// The other tests without a feature tag. + later: ParseCounts, + with_features: usize, + modules: usize, +} + +/// Parses each of `files` in the modes its flags give. With `any_edition`, every test without a +/// feature tag is counted in [`ParseRun::main`]; otherwise only those that name an ES5 section. +fn parse_files(dir: &Path, files: &[PathBuf], any_edition: bool) -> Result { + // VECTORCRAFT_TEST262_VERBOSE=1 prints each test before it is parsed. + let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); + let mut run = ParseRun::default(); + for path in files { + let source = read_source(path)?; + let meta = meta(&source); + if !meta.features.is_empty() { + run.with_features += 1; + continue; + } + if !eligible(&meta, true) { + run.modules += 1; + continue; + } + let counts = if eligible(&meta, any_edition) { &mut run.main } else { &mut run.later }; + if meta.negative_phase.as_deref() == Some("parse") { + counts.negative += 1; + } else { + counts.positive += 1; + } + let rel = path.strip_prefix(dir).unwrap_or(path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + if verbose { + eprintln!("{} ({mode})", path.display()); + } + match parse_check(&source, &meta, strict) { + Ok(()) => counts.passed += 1, + Err(outcome) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n")); + } + } + } + } + Ok(run) +} + +/// Parses `source` as sloppy or strict mode code (with `"use strict";` before it); `Err` describes +/// a result other than the one the metadata expects (a `SyntaxError` for `negative: phase: parse`). +fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> { + let expect_error = meta.negative_phase.as_deref() == Some("parse"); + let text = if strict { format!("\"use strict\";\n{source}") } else { source.to_string() }; + match parse(&text, &Options::default()) { + Ok(_) if expect_error => Err("parsed; a SyntaxError was expected".to_string()), + Err(e) if !expect_error => Err(e.to_string()), + _ => Ok(()), + } +} + /// Globals and method names the interpreter does not provide yet: a test that names one, in its /// own source or in a harness file it includes, is skipped. const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ @@ -233,6 +379,14 @@ const ES5_BUILT_INS: &[&str] = &[ "annexB/built-ins/unescape", ]; +/// The tests of the Annex B syntax and semantics (ECMA-262 Annex B.1 and B.3). +const ANNEX_B_LANGUAGE: &str = "annexB/language"; + +/// The folders under `test/annexB/built-ins/` with tests without a feature tag, other than the +/// `escape` and `unescape` folders [`ES5_BUILT_INS`] runs: `substr`, `getYear`, `setYear`, +/// `toGMTString`, the legacy `RegExp` features and the `Function` tests. +const ANNEX_B_BUILT_INS: &[&str] = &["annexB/built-ins/Date", "annexB/built-ins/Function", "annexB/built-ins/RegExp", "annexB/built-ins/String"]; + /// The names in [`MISSING_BUILTINS`] that `String`, `Number`, `RegExp` and `Date` provide. const TEXT_BUILTINS: &str = "String Number Date RegExp charAt charCodeAt fromCharCode substring substr split replace match search exec test \ toUpperCase toLowerCase trim toFixed toPrecision toExponential now"; @@ -335,10 +489,20 @@ impl RunCounts { self.tests, self.passed, self.failed, self.panicked, self.skipped ) } + + /// Adds the counts and failures of `other`. + fn add(&mut self, other: RunCounts) { + self.tests += other.tests; + self.skipped += other.skipped; + self.passed += other.passed; + self.failed += other.failed; + self.panicked += other.panicked; + self.failures.push_str(&other.failures); + } } fn run_language_subset(dir: &Path) { - let language = dir.join("test").join("language"); + let language = or_fail(inside(dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); let missing = missing_builtins(&[TEXT_BUILTINS]); let (es5, _) = run_tests(dir, &language, &missing, false); @@ -377,17 +541,11 @@ fn run_built_ins(dir: &Path) { let missing = missing_builtins(&[TEXT_BUILTINS]); let mut all = RunCounts::default(); for folder in ES5_BUILT_INS { - let root = dir.join("test").join(folder); + let root = or_fail(inside(dir, &format!("test/{folder}"))); assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); let (es5, later) = run_tests(dir, &root, &missing, folder.starts_with("annexB")); - for counts in [es5, later] { - all.tests += counts.tests; - all.skipped += counts.skipped; - all.passed += counts.passed; - all.failed += counts.failed; - all.panicked += counts.panicked; - all.failures.push_str(&counts.failures); - } + all.add(es5); + all.add(later); } assert!(all.tests > 0, "no ES5 built-ins tests ran under {}", dir.display()); let report = dir.join("built-ins-failures.txt"); @@ -414,7 +572,7 @@ fn run_text_builtins(dir: &Path) { let mut report = String::new(); let mut panicked = 0; for name in ["String", "Number", "RegExp", "Date"] { - let root = dir.join("test").join("built-ins").join(name); + let root = or_fail(inside(dir, &format!("test/built-ins/{name}"))); assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); let missing = if name == "String" { missing_builtins(&[TEXT_BUILTINS, STRING_METHODS_SHARED_WITH_ARRAY]) } else { missing_builtins(&[TEXT_BUILTINS]) }; @@ -436,39 +594,27 @@ fn run_text_builtins(dir: &Path) { /// negative parse tests, each in a new realm after the harness. Returns the counts for the tests /// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out). fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> (RunCounts, RunCounts) { - let harness_dir = dir.join("harness"); - let read = |p: &Path| { - let bytes = std::fs::read(p).map_err(|e| format!("cannot read {}: {e}", p.display())); - assert!(bytes.is_ok(), "{}", bytes.as_ref().err().map_or("", String::as_str)); - String::from_utf8_lossy(&bytes.unwrap_or_default()).into_owned() - }; - let prelude = format!("{}\n{}\n", read(&harness_dir.join("assert.js")), read(&harness_dir.join("sta.js"))); + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); let (mut es5_counts, mut later_counts) = (RunCounts::default(), RunCounts::default()); - for path in test_files(root) { - let source = read(&path); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); let meta = meta(&source); - let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")); - if (!meta.es5 && !later) || !meta.features.is_empty() || negative_parse || meta.flags.iter().any(|f| f == "module") { + if !eligible(&meta, later) || meta.negative_phase.as_deref() == Some("parse") { continue; } let counts = if meta.es5 { &mut es5_counts } else { &mut later_counts }; - let includes: String = meta.includes.iter().map(|i| read(&harness_dir.join(i)) + "\n").collect(); + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); if meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { counts.skipped += 1; continue; } counts.tests += 1; let has = |flag: &str| meta.flags.iter().any(|f| f == flag); - let modes: &[bool] = if has("raw") || has("noStrict") { - &[false] - } else if has("onlyStrict") { - &[true] - } else { - &[false, true] - }; let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); - for &strict in modes { + for &strict in modes(&meta) { let mode = if strict { "strict" } else { "sloppy" }; if verbose { eprintln!("{rel} ({mode})"); @@ -494,6 +640,62 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> ( (es5_counts, later_counts) } +#[test] +fn annex_b_runs() { + let Some(dir) = suite_dir() else { + println!("test262 Annex B interpreter: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_annex_b(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests without a feature tag under [`ANNEX_B_LANGUAGE`] and under each folder +/// [`ANNEX_B_BUILT_INS`] names, of any edition, prints the counts of each and writes the failures +/// to `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. +fn run_annex_b(dir: &Path) { + if or_fail(present(dir, "test/annexB")).is_none() { + println!("test262 Annex B interpreter: SKIPPED ({} has no test/annexB)", dir.display()); + return; + } + let mut panicked = 0; + let mut built_ins_report = String::new(); + for folder in std::iter::once(&ANNEX_B_LANGUAGE).chain(ANNEX_B_BUILT_INS) { + let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else { + assert!(*folder != ANNEX_B_LANGUAGE, "{} has test/annexB but no test/{folder}", dir.display()); + println!("test262 {folder}: SKIPPED (not in this suite)"); + continue; + }; + let missing = if folder.ends_with("/String") { + missing_builtins(&[TEXT_BUILTINS, STRING_METHODS_SHARED_WITH_ARRAY]) + } else { + missing_builtins(&[TEXT_BUILTINS]) + }; + let (es5, later) = run_tests(dir, &root, &missing, true); + let mut counts = RunCounts::default(); + counts.add(es5); + counts.add(later); + assert!(counts.tests > 0, "no Annex B tests ran under {}", root.display()); + panicked += counts.panicked; + println!("test262 {folder} through the interpreter: {}.", counts.summary()); + if *folder == ANNEX_B_LANGUAGE { + let path = dir.join("annexb-language-failures.txt"); + if let Err(e) = std::fs::write(&path, &counts.failures) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 {folder} failures: {}", path.display()); + } else { + built_ins_report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + } + } + let path = dir.join("annexb-builtins-failures.txt"); + if let Err(e) = std::fs::write(&path, &built_ins_report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 Annex B built-ins failures: {}", path.display()); + assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); @@ -558,3 +760,153 @@ fn a_source_that_does_not_parse_as_es5_skips() { assert!(skips(&["var x = 1;", "const y = 2;"])); assert!(skips(&["var s = `${x}`;"])); } + +#[test] +fn annex_b_runs_read_the_language_tree_and_the_built_ins_folders_not_run_elsewhere() { + assert_eq!(ANNEX_B_LANGUAGE, "annexB/language"); + for folder in ["annexB/built-ins/String", "annexB/built-ins/Date", "annexB/built-ins/RegExp", "annexB/built-ins/Function"] { + assert!(ANNEX_B_BUILT_INS.contains(&folder), "{folder} is not read"); + } + // `escape` and `unescape` run with the ES5 built-ins, so they are not run twice. + for folder in ANNEX_B_BUILT_INS { + assert!(!ES5_BUILT_INS.contains(folder), "{folder} runs twice"); + assert!(folder.starts_with("annexB/built-ins/"), "{folder} is not an Annex B built-ins folder"); + } +} + +/// A test written for a later edition, naming its section with `esid:` only. +const ESID_ONLY: &str = "/*---\nesid: sec-example\ndescription: a test of a later edition\n---*/\nvar a = 1;\n"; + +#[test] +fn tests_that_name_only_a_later_section_are_read_with_any_edition() { + let later = meta(ESID_ONLY); + assert!(!later.es5); + assert!(eligible(&later, true)); + assert!(!eligible(&later, false)); + let es5 = meta("/*---\nes5id: 12.6.4\n---*/\nvar a = 1;\n"); + assert!(eligible(&es5, false)); + let tagged = meta("/*---\nesid: sec-example\nfeatures: [let]\n---*/\nlet a = 1;\n"); + assert!(!eligible(&tagged, true)); + let module = meta("/*---\nesid: sec-example\nflags: [module]\n---*/\nvar a = 1;\n"); + assert!(!eligible(&module, true)); +} + +/// A strict-only test that expects a `SyntaxError` for an initializer on a for-in variable. +const STRICT_FOR_IN_INITIALIZER: &str = + "/*---\nesid: sec-example\nnegative:\n phase: parse\n type: SyntaxError\nflags: [onlyStrict]\n---*/\nfor (var a = 0 in {}) {}\n"; + +/// A sloppy-only test with an initializer on a for-in variable, which must parse. +const SLOPPY_FOR_IN_INITIALIZER: &str = "/*---\nesid: sec-example\nflags: [noStrict]\n---*/\nvar n = 0;\nfor (var a = 1 in {}) { n += 1; }\n"; + +#[test] +fn a_for_in_initializer_is_a_syntax_error_in_strict_code_only() { + let strict = meta(STRICT_FOR_IN_INITIALIZER); + assert_eq!(strict.negative_phase.as_deref(), Some("parse")); + assert_eq!(modes(&strict), &[true]); + assert_eq!(parse_check(STRICT_FOR_IN_INITIALIZER, &strict, true), Ok(())); + assert!(parse_check(STRICT_FOR_IN_INITIALIZER, &strict, false).is_err(), "the initializer parses in sloppy code"); + + let sloppy = meta(SLOPPY_FOR_IN_INITIALIZER); + assert_eq!(sloppy.negative_phase, None); + assert_eq!(modes(&sloppy), &[false]); + assert_eq!(parse_check(SLOPPY_FOR_IN_INITIALIZER, &sloppy, false), Ok(())); + assert!(parse_check(SLOPPY_FOR_IN_INITIALIZER, &sloppy, true).is_err(), "the initializer parses in strict code"); + + assert_eq!(modes(&meta(ESID_ONLY)), &[false, true]); + assert_eq!(modes(&meta("/*---\nflags: [raw]\n---*/\n")), &[false]); +} + +/// A new, empty folder under the system's temporary folder for one test. +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vectorcraft-test262-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + or_fail(std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))); + dir +} + +#[test] +fn the_walk_reads_only_test_files_inside_the_folder() { + let dir = scratch("walk"); + std::fs::create_dir_all(dir.join("suite/sub")).unwrap(); + std::fs::write(dir.join("suite/b.js"), "").unwrap(); + std::fs::write(dir.join("suite/sub/a.js"), "").unwrap(); + std::fs::write(dir.join("suite/c_FIXTURE.js"), "").unwrap(); + std::fs::write(dir.join("suite/notes.txt"), "").unwrap(); + assert_eq!(test_files(&dir.join("suite")), Ok(vec![dir.join("suite/b.js"), dir.join("suite/sub/a.js")])); + assert!(test_files(&dir.join("absent")).is_err(), "a missing folder is skipped silently"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[cfg(unix)] +#[test] +fn the_walk_does_not_follow_symbolic_links() { + let dir = scratch("links"); + std::fs::create_dir_all(dir.join("suite")).unwrap(); + std::fs::create_dir_all(dir.join("outside")).unwrap(); + std::fs::write(dir.join("outside/x.js"), "").unwrap(); + std::fs::write(dir.join("suite/a.js"), "").unwrap(); + std::os::unix::fs::symlink(dir.join("outside"), dir.join("suite/linked")).unwrap(); + std::os::unix::fs::symlink(dir.join("outside/x.js"), dir.join("suite/x.js")).unwrap(); + assert_eq!(test_files(&dir.join("suite")), Ok(vec![dir.join("suite/a.js")])); + assert!(read_source(&dir.join("suite/x.js")).is_err(), "a linked file is read"); + assert!(inside(&dir.join("suite"), "linked/x.js").is_err(), "a path through a linked folder is allowed"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn harness_names_stay_inside_the_suite() { + let dir = Path::new("suite"); + assert_eq!(inside(dir, "harness/compareArray.js"), Ok(dir.join("harness").join("compareArray.js"))); + for name in ["harness/../../secret.js", "harness/./a.js", "/etc/passwd", "harness//a.js", "harness/a\\..\\b.js", "harness/C:a.js", ""] { + assert!(inside(dir, name).is_err(), "{name:?} is allowed"); + } +} + +#[test] +fn an_unreadable_annex_b_folder_fails_and_only_an_absent_one_skips() { + let dir = scratch("present"); + std::fs::create_dir_all(dir.join("test/annexB")).unwrap(); + assert_eq!(present(&dir, "test/annexB"), Ok(Some(dir.join("test").join("annexB")))); + assert_eq!(present(&dir, "test/annexB/language"), Ok(None)); + // A NUL byte in the path makes its metadata unreadable on every platform. + assert!(present(Path::new("suite\0dir"), "test/annexB").is_err(), "a path whose metadata cannot be read is skipped as absent"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn an_annex_b_folder_whose_tests_are_all_skipped_fails() { + let dir = scratch("all-skipped"); + std::fs::create_dir_all(dir.join("harness")).unwrap(); + std::fs::create_dir_all(dir.join("test/annexB/language")).unwrap(); + std::fs::write(dir.join("harness/assert.js"), "").unwrap(); + std::fs::write(dir.join("harness/sta.js"), "").unwrap(); + std::fs::write(dir.join("test/annexB/language/a.js"), "/*---\nesid: sec-x\nflags: [async]\n---*/\n").unwrap(); + let outcome = std::panic::catch_unwind(|| run_annex_b(&dir)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(outcome.is_err(), "a folder where every test is skipped passes"); +} + +#[test] +fn an_annex_b_tree_without_its_language_folder_fails() { + let dir = scratch("no-language"); + std::fs::create_dir_all(dir.join("harness")).unwrap(); + std::fs::create_dir_all(dir.join("test/annexB/built-ins")).unwrap(); + std::fs::write(dir.join("harness/assert.js"), "").unwrap(); + std::fs::write(dir.join("harness/sta.js"), "").unwrap(); + let parsed = std::panic::catch_unwind(|| parse_annex_b(&dir)); + let ran = std::panic::catch_unwind(|| run_annex_b(&dir)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(parsed.is_err(), "the parse test skips a suite without test/annexB/language"); + assert!(ran.is_err(), "the interpreter test skips a suite without test/annexB/language"); +} + +#[test] +fn a_file_over_the_limit_is_refused_before_it_is_read() { + let dir = scratch("size"); + let path = dir.join("big.js"); + std::fs::File::create(&path).unwrap().set_len(MAX_FILE_BYTES + 1).unwrap(); + assert!(read_source(&path).is_err_and(|e| e.contains("over the")), "an oversized file is read"); + std::fs::File::create(&path).unwrap().set_len(4).unwrap(); + assert_eq!(read_source(&path), Ok("\0\0\0\0".to_string())); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 6a95469d92..c8756cefc7 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1710,8 +1710,16 @@ fn transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing() { assert_eq!(applied["isError"], false, "{applied}"); let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); assert_eq!(applied["applied"], json!(["move"])); - let applied = call(&mut s, 21, "transform", json!({"ids": [second], "rotate": 90, "origin": null})); + let unturned = inspect(&mut s, 21)["layers"].clone(); + let applied = call(&mut s, 22, "transform", json!({"ids": [second], "rotate": 90, "origin": null})); assert_eq!(applied["isError"], false, "{applied}"); + let turned = inspect(&mut s, 23)["layers"].clone(); + assert_ne!(turned, unturned, "the rotation must change the path"); + // A null `origin` turns about the same default pivot as an omitted one. + assert_eq!(call(&mut s, 24, "undo", json!({}))["isError"], false); + let applied = call(&mut s, 25, "transform", json!({"ids": [second], "rotate": 90})); + assert_eq!(applied["isError"], false, "{applied}"); + assert_eq!(inspect(&mut s, 26)["layers"], turned); // The schema allows null for every argument but `ids`. let tools = tool_definitions(); let props = &tools.iter().find(|t| t["name"] == "transform").unwrap()["inputSchema"]["properties"]; diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index 408e6166a1..1026a54c4b 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,19 +3,20 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader" +description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader" [lints] workspace = true [dependencies] +craft-codepage = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } -craft-metafile = { workspace = true } +craft-metafile = { workspace = true, features = ["write"] } kurbo = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } diff --git a/crates/metafile/src/bytes.rs b/crates/metafile/src/bytes.rs index 133a476866..3c4d85a1c5 100644 --- a/crates/metafile/src/bytes.rs +++ b/crates/metafile/src/bytes.rs @@ -1,4 +1,4 @@ -//! Little-endian values: the buffer both writers build records in. +//! Little-endian values for hand-built import fixtures. /// Bytes being written. #[derive(Default)] @@ -20,9 +20,6 @@ impl Out { pub fn i32(&mut self, v: i32) { self.0.extend_from_slice(&v.to_le_bytes()); } - pub fn f32(&mut self, v: f32) { - self.0.extend_from_slice(&v.to_le_bytes()); - } pub fn bytes(&mut self, b: &[u8]) { self.0.extend_from_slice(b); } @@ -32,15 +29,4 @@ impl Out { self.0.push(0); } } - /// Overwrite the `u32` at `at` (a size or count known only later). - pub fn set_u32(&mut self, at: usize, v: u32) { - if let Some(b) = self.0.get_mut(at..at + 4) { - b.copy_from_slice(&v.to_le_bytes()); - } - } - pub fn set_i32(&mut self, at: usize, v: i32) { - if let Some(b) = self.0.get_mut(at..at + 4) { - b.copy_from_slice(&v.to_le_bytes()); - } - } } diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index b104304d7f..3440daccd4 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -1,6 +1,6 @@ -//! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit -//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source). +//! App bitmap sizing, read budgets, and raster conversion for imported pictures. +use craft_metafile::write::Image; use vectorcraft_doc::resample::{Resample, resized}; /// Most pixels along a side of an image the writers store (larger ones are scaled down). @@ -16,8 +16,6 @@ pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28; /// What [`charge`] says of a bitmap past what is left of the file's budget. pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may"; -const BI_RGB: u32 = 0; - /// Pixels with straight (not premultiplied) alpha, row by row from the top. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Rgba { @@ -26,30 +24,25 @@ pub(crate) struct Rgba { pub pixels: Vec, } +/// `img`, scaled down to what a metafile stores when it is larger. +pub(crate) fn fitted(img: image::RgbaImage) -> Image { + let (w, h) = img.dimensions(); + let side = f64::from(w.max(h)) / f64::from(MAX_SIDE); + let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64; + let k = side.max(area.sqrt()); + let img = if k > 1.0 { + let nw = ((f64::from(w) / k).floor() as u32).max(1); + let nh = ((f64::from(h) / k).floor() as u32).max(1); + let how = Resample::Filter(image::imageops::FilterType::Triangle); + resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8() + } else { + img + }; + let (width, height) = img.dimensions(); + Image { width, height, rgba: img.into_raw() } +} + impl Rgba { - /// `img`, scaled down to what a metafile stores when it is larger. - pub fn fitted(img: image::RgbaImage) -> Self { - let (w, h) = img.dimensions(); - let side = f64::from(w.max(h)) / f64::from(MAX_SIDE); - let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64; - let k = side.max(area.sqrt()); - let img = if k > 1.0 { - let nw = ((f64::from(w) / k).floor() as u32).max(1); - let nh = ((f64::from(h) / k).floor() as u32).max(1); - let how = Resample::Filter(image::imageops::FilterType::Triangle); - resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8() - } else { - img - }; - let (width, height) = img.dimensions(); - Self { width, height, pixels: img.into_raw() } - } - - /// Every pixel fully opaque? - pub fn opaque(&self) -> bool { - self.pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255) - } - /// As PNG bytes. pub fn to_png(&self) -> Result, String> { let img = craft_image_codecs::Image::from_u8(self.width, self.height, craft_image_codecs::ChannelLayout::Rgba, self.pixels.clone()) @@ -58,63 +51,6 @@ impl Rgba { } } -/// A BITMAPINFOHEADER of a bottom-up, uncompressed `width` × `height` bitmap of `bits` per pixel. -fn header(width: u32, height: u32, bits: u16, size: usize) -> Vec { - let mut h = crate::bytes::Out::default(); - h.u32(40); - h.i32(i32::try_from(width).unwrap_or(i32::MAX)); - h.i32(i32::try_from(height).unwrap_or(i32::MAX)); - h.u16(1); - h.u16(bits); - h.u32(BI_RGB); - h.u32(u32::try_from(size).unwrap_or(0)); - // 2835 pixels a metre: 72 ppi (the size on the page comes from the record). - h.i32(2835); - h.i32(2835); - h.u32(0); - h.u32(0); - h.0 -} - -/// The bytes of a row of `width` pixels of `bits` each, padded to 4 bytes. -fn stride(width: u32, bits: u32) -> Option { - let row_bits = u64::from(width).checked_mul(u64::from(bits))?; - usize::try_from(row_bits.div_ceil(32) * 4).ok() -} - -/// `img` at `opacity`, composited over white, as a 24-bit DIB → (header, bits). -pub(crate) fn rgb24(img: &Rgba, opacity: f32) -> (Vec, Vec) { - let row = stride(img.width, 24).unwrap_or(0); - let mut bits = vec![0u8; row * img.height as usize]; - let over = |c: u8, a: u32| ((u32::from(c) * a + 255 * (255 - a) + 127) / 255) as u8; - for (y, src) in img.pixels.chunks_exact((img.width as usize * 4).max(1)).enumerate() { - // Bottom-up: the first stored row is the image's last. - let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue }; - let Some(dst) = bits.get_mut(at..at + img.width as usize * 3) else { continue }; - for (d, p) in dst.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<4>().0) { - let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32; - d.copy_from_slice(&[over(p[2], a), over(p[1], a), over(p[0], a)]); - } - } - (header(img.width, img.height, 24, bits.len()), bits) -} - -/// `img` at `opacity` as a 32-bit DIB of premultiplied BGRA → (header, bits). -pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec, Vec) { - let row = img.width as usize * 4; - let mut bits = vec![0u8; row * img.height as usize]; - for (y, src) in img.pixels.chunks_exact(row.max(1)).enumerate() { - let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue }; - let Some(dst) = bits.get_mut(at..at + row) else { continue }; - for (d, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) { - let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32; - let pre = |c: u8| ((u32::from(c) * a + 127) / 255) as u8; - d.copy_from_slice(&[pre(p[2]), pre(p[1]), pre(p[0]), a as u8]); - } - } - (header(img.width, img.height, 32, bits.len()), bits) -} - /// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { let n = u64::from(w) * u64::from(h); @@ -126,10 +62,10 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { mod tests { use super::*; - fn sample() -> Rgba { + fn sample() -> Image { // 3 × 2: red, green, blue / half-transparent black, transparent, white. let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]; - Rgba { width: 3, height: 2, pixels } + Image { width: 3, height: 2, rgba: pixels } } #[test] @@ -144,7 +80,14 @@ mod tests { #[test] fn rgb24_is_bottom_up_bgr_over_white() { - let (bmi, bits) = rgb24(&sample(), 1.0); + // WMF's shared writer emits a StretchDIB record: 28 bytes of parameters and + // record framing precede BITMAPINFOHEADER, then the bottom-up rows. + let image = std::sync::Arc::new(sample()); + let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity: 1.0 }; + let bytes = craft_metafile::write::wmf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0)).unwrap().bytes; + let records = crate::tests::wmf_records(&bytes); + let (_, record) = records.iter().find(|(kind, _)| *kind == 0x0f43).unwrap(); + let (bmi, bits) = (&record[28..68], &record[68..]); assert_eq!(bmi.len(), 40); assert_eq!(&bmi[14..16], &[24, 0], "24 bits a pixel"); // Rows of 9 bytes padded to 12, the last row first: half-transparent black over white is @@ -154,19 +97,28 @@ mod tests { #[test] fn bgra32_is_premultiplied() { - let (bmi, bits) = bgra32(&sample(), 1.0); - assert_eq!(&bmi[14..16], &[32, 0]); + let pixels = |opacity| { + let image = std::sync::Arc::new(sample()); + let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity }; + let bytes = craft_metafile::write::emf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0), "VectorCraft", "").unwrap(); + let records = crate::tests::emf_records(&bytes); + let (_, record) = records.iter().find(|(kind, _)| *kind == 114).unwrap(); + let (bmi, bits) = (&record[108..148], &record[148..]); + assert_eq!(&bmi[14..16], &[32, 0]); + bits.to_vec() + }; + let bits = pixels(1.0); assert_eq!(&bits[..12], &[0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]); assert_eq!(&bits[12..16], &[0, 0, 255, 255], "red, as BGRA"); // At half opacity. - let (_, half) = bgra32(&sample(), 0.5); + let half = pixels(0.5); assert_eq!(&half[12..16], &[0, 0, 128, 128]); } #[test] fn large_images_are_scaled_to_fit() { let img = image::RgbaImage::new(MAX_SIDE * 2, 4); - let f = Rgba::fitted(img); + let f = fitted(img); assert_eq!((f.width, f.height), (MAX_SIDE, 2)); } @@ -176,10 +128,10 @@ mod tests { fn large_images_keep_their_color_beside_clear_pixels() { let img = image::RgbaImage::from_fn(MAX_SIDE * 2, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }); - let f = Rgba::fitted(img); + let f = fitted(img); assert_eq!((f.width, f.height), (MAX_SIDE, 2)); let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8; - for p in f.pixels.as_chunks::<4>().0 { + for p in f.rgba.as_chunks::<4>().0 { assert!(p[3] > 0 && [200, 30, 30].iter().zip(p).all(|(&want, &c)| m(c, p[3]).abs_diff(m(want, p[3])) <= 1), "{p:?}"); } } diff --git a/crates/metafile/src/emf.rs b/crates/metafile/src/emf.rs deleted file mode 100644 index dccfb4326b..0000000000 --- a/crates/metafile/src/emf.rs +++ /dev/null @@ -1,503 +0,0 @@ -//! The EMF writer: an EMR_HEADER whose frame is the region in 0.01 mm, then the drawing in device -//! units of 0.01 mm (the reference device has 100 pixels a millimetre) and an EMR_EOF. -//! -//! Each fill and stroke is a path bracket (move-to, poly-line-to and poly-Bézier-to runs, close -//! figure) filled with a solid brush or stroked with a geometric pen; brushes and pens are made -//! when the colour or pen changes and deleted when replaced. Clips are path clips inside a saved -//! DC; images are StretchDIBits (opaque) or AlphaBlend (with transparency) under a world transform -//! that places their pixels. - -use kurbo::PathEl; -use vectorcraft_doc::{LineCap, LineJoin}; -use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect}; - -use crate::bytes::Out; -use crate::dib::{self, Rgba}; -use crate::scene::{Op, Pen}; - -// Record types (MS-EMF 2.1.1). -pub(crate) const HEADER: u32 = 1; -pub(crate) const POLYBEZIERTO: u32 = 5; -pub(crate) const POLYLINETO: u32 = 6; -pub(crate) const EOF: u32 = 14; -pub(crate) const SETBKMODE: u32 = 18; -pub(crate) const SETPOLYFILLMODE: u32 = 19; -pub(crate) const MOVETOEX: u32 = 27; -pub(crate) const SAVEDC: u32 = 33; -pub(crate) const RESTOREDC: u32 = 34; -pub(crate) const SETWORLDTRANSFORM: u32 = 35; -pub(crate) const MODIFYWORLDTRANSFORM: u32 = 36; -pub(crate) const SELECTOBJECT: u32 = 37; -pub(crate) const CREATEBRUSHINDIRECT: u32 = 39; -pub(crate) const DELETEOBJECT: u32 = 40; -pub(crate) const SETMITERLIMIT: u32 = 58; -pub(crate) const BEGINPATH: u32 = 59; -pub(crate) const ENDPATH: u32 = 60; -pub(crate) const CLOSEFIGURE: u32 = 61; -pub(crate) const FILLPATH: u32 = 62; -pub(crate) const STROKEPATH: u32 = 64; -pub(crate) const SELECTCLIPPATH: u32 = 67; -pub(crate) const STRETCHDIBITS: u32 = 81; -pub(crate) const EXTCREATEPEN: u32 = 95; -pub(crate) const ALPHABLEND: u32 = 114; - -/// The `" EMF"` signature in the header. -pub(crate) const SIGNATURE: u32 = 0x464D_4520; -/// Stock objects (selected to release ours before deleting them). -const WHITE_BRUSH: u32 = 0x8000_0000; -const NULL_PEN: u32 = 0x8000_0008; -/// Our two object slots (0 is reserved). -const BRUSH: u32 = 1; -const PEN: u32 = 2; - -pub(crate) const PS_GEOMETRIC: u32 = 0x0001_0000; -pub(crate) const PS_USERSTYLE: u32 = 7; -pub(crate) const PS_ENDCAP_SQUARE: u32 = 0x100; -pub(crate) const PS_ENDCAP_FLAT: u32 = 0x200; -pub(crate) const PS_JOIN_BEVEL: u32 = 0x1000; -pub(crate) const PS_JOIN_MITER: u32 = 0x2000; -/// Raster operation: copy the source. -pub(crate) const SRCCOPY: u32 = 0x00CC_0020; - -/// Device units (0.01 mm) per point. -pub(crate) const UNITS_PER_PT: f64 = 2540.0 / 72.0; -/// Longest dash pattern a geometric pen takes (longer ones are drawn as separate dashes). -const MAX_STYLE: usize = 16; -/// Header size with both extensions. -const HEADER_SIZE: usize = 108; -/// Coordinates are kept within this (far beyond any page). -const MAX_COORD: f64 = 1e9; - -/// Does `bytes` start with an EMF header? -pub(crate) fn is_emf(bytes: &[u8]) -> bool { - let u32_at = |at: usize| bytes.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); - u32_at(0) == Some(HEADER) && u32_at(40) == Some(SIGNATURE) -} - -/// A COLORREF (0x00bbggrr). -pub(crate) fn colorref(rgb: [u8; 3]) -> u32 { - u32::from_le_bytes([rgb[0], rgb[1], rgb[2], 0]) -} - -/// What a pen object is made of, to tell when the next stroke needs another. -#[derive(Clone, PartialEq)] -struct PenKey { - style: u32, - width: u32, - color: u32, - entries: Vec, -} - -/// A device-space bounding box (inclusive). -type Bounds = [i32; 4]; - -fn union(a: Option, b: Bounds) -> Bounds { - match a { - None => b, - Some(a) => [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])], - } -} - -struct Writer { - out: Out, - records: u32, - /// Document → device units. - to_dev: Affine, - /// The frame in device units: what the region clip lets through. - frame: Bounds, - /// Everything drawn, in device units. - bounds: Option, - brush: Option, - pen: Option, - fill_mode: Option, - miter: Option, -} - -/// Write `ops` as an EMF of `region` (document space), described as `title`. -pub(crate) fn write(ops: &[Op], region: Rect, title: &str) -> Vec { - let k = UNITS_PER_PT; - let frame = [0, 0, (region.width() * k).round() as i32, (region.height() * k).round() as i32]; - let mut w = Writer { - out: Out::default(), - records: 0, - to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()), - frame, - bounds: None, - brush: None, - pen: None, - fill_mode: None, - miter: None, - }; - w.header(title); - // Dash gaps and hatches show what is below. - w.record(SETBKMODE, |o| o.u32(1)); - for op in ops { - w.op(op); - } - w.release(); - w.record(EOF, |o| { - o.u32(0); - o.u32(16); - o.u32(20); - }); - w.finish() -} - -impl Writer { - /// Append one record: its type, size and `body`, padded to 4 bytes. - fn record(&mut self, kind: u32, body: impl FnOnce(&mut Out)) { - let start = self.out.len(); - self.out.u32(kind); - self.out.u32(0); - body(&mut self.out); - self.out.pad(4); - let size = u32::try_from(self.out.len() - start).unwrap_or(u32::MAX); - self.out.set_u32(start + 4, size); - self.records += 1; - } - - fn header(&mut self, title: &str) { - let desc: Vec = - "VectorCraft".encode_utf16().chain([0]).chain(title.chars().take(200).collect::().encode_utf16()).chain([0, 0]).collect(); - let f = self.frame; - // The reference device: 100 pixels a millimetre, as large as the frame. - let mm = [(f[2] / 100).max(1) + 1, (f[3] / 100).max(1) + 1]; - self.record(HEADER, |o| { - // Bounds, patched in `finish`. - o.bytes(&[0; 16]); - for v in f { - o.i32(v); - } - o.u32(SIGNATURE); - o.u32(0x0001_0000); - // Bytes, records and handles, patched in `finish`. - o.u32(0); - o.u32(0); - o.u16(3); - o.u16(0); - o.u32(desc.len() as u32); - o.u32(HEADER_SIZE as u32); - o.u32(0); - o.i32(mm[0] * 100); - o.i32(mm[1] * 100); - o.i32(mm[0]); - o.i32(mm[1]); - // No pixel format, not OpenGL; the device in micrometres. - o.u32(0); - o.u32(0); - o.u32(0); - o.u32(mm[0] as u32 * 1000); - o.u32(mm[1] as u32 * 1000); - for c in &desc { - o.u16(*c); - } - }); - } - - /// Patch the header's bounds, size and record count. - fn finish(mut self) -> Vec { - let b = self.bounds.map(|b| [b[0].max(self.frame[0]), b[1].max(self.frame[1]), b[2].min(self.frame[2]), b[3].min(self.frame[3])]); - // An empty picture has bounds (0, 0, -1, -1). - let b = b.filter(|b| b[0] <= b[2] && b[1] <= b[3]).unwrap_or([0, 0, -1, -1]); - for (i, v) in b.iter().enumerate() { - self.out.set_i32(8 + 4 * i, *v); - } - let size = u32::try_from(self.out.len()).unwrap_or(u32::MAX); - self.out.set_u32(48, size); - self.out.set_u32(52, self.records); - self.out.0 - } - - fn dev(&self, p: Point) -> [i32; 2] { - let q = self.to_dev * p; - let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_COORD, MAX_COORD) as i32 } else { 0 }; - [c(q.x), c(q.y)] - } - - fn grow(&mut self, b: Bounds) { - self.bounds = Some(union(self.bounds, b)); - } - - fn op(&mut self, op: &Op) { - match op { - Op::Fill { path, rule, rgb } => { - self.fill_mode(*rule); - self.brush(*rgb); - if let Some(b) = self.path(path) { - self.grow(b); - self.record(FILLPATH, |o| b.iter().for_each(|v| o.i32(*v))); - } - } - Op::Stroke { path, pen } => { - let dashed; - let path = if self.pen(pen) { - path - } else { - dashed = crate::scene::dashed(path, pen.dash.as_ref()); - &dashed - }; - if let Some(b) = self.path(path) { - let half = (pen.width * UNITS_PER_PT / 2.0).ceil() as i32; - let b = [b[0] - half, b[1] - half, b[2] + half, b[3] + half]; - self.grow(b); - self.record(STROKEPATH, |o| b.iter().for_each(|v| o.i32(*v))); - } - } - Op::Image { image, xf, opacity } => self.image(image, *xf, *opacity), - Op::Clip { path, rule } => { - self.release(); - self.record(SAVEDC, |_| {}); - self.fill_mode(*rule); - if self.path(path).is_some() { - // RGN_AND: inside the clip already set. - self.record(SELECTCLIPPATH, |o| o.u32(1)); - } - } - Op::Unclip => { - self.release(); - self.record(RESTOREDC, |o| o.i32(-1)); - // The DC's fill mode and miter limit are back to what they were at the save. - self.fill_mode = None; - self.miter = None; - } - } - } - - fn fill_mode(&mut self, rule: FillRule) { - // ALTERNATE (even-odd) or WINDING (non-zero). - let mode = if rule == FillRule::EvenOdd { 1 } else { 2 }; - if self.fill_mode != Some(mode) { - self.record(SETPOLYFILLMODE, |o| o.u32(mode)); - self.fill_mode = Some(mode); - } - } - - /// Select a solid brush of `rgb`, made when the colour changes. - fn brush(&mut self, rgb: [u8; 3]) { - let color = colorref(rgb); - if self.brush == Some(color) { - return; - } - self.drop_brush(); - self.record(CREATEBRUSHINDIRECT, |o| { - o.u32(BRUSH); - // BS_SOLID, the colour, no hatch. - o.u32(0); - o.u32(color); - o.u32(0); - }); - self.record(SELECTOBJECT, |o| o.u32(BRUSH)); - self.brush = Some(color); - } - - fn drop_brush(&mut self) { - if self.brush.take().is_some() { - self.record(SELECTOBJECT, |o| o.u32(WHITE_BRUSH)); - self.record(DELETEOBJECT, |o| o.u32(BRUSH)); - } - } - - fn drop_pen(&mut self) { - if self.pen.take().is_some() { - self.record(SELECTOBJECT, |o| o.u32(NULL_PEN)); - self.record(DELETEOBJECT, |o| o.u32(PEN)); - } - } - - /// Release our objects (before a DC is saved or restored, which would bring back deleted ones). - fn release(&mut self) { - self.drop_brush(); - self.drop_pen(); - } - - /// Select a geometric pen for `p`, made when it changes. False when `p`'s dashes must be - /// drawn as separate lines (the pen selected is solid): a pen's dashes start at the path's - /// start, every entry at least a unit long, 16 entries at most. - fn pen(&mut self, p: &Pen) -> bool { - let k = UNITS_PER_PT; - let entries: Option> = p.dash.as_ref().map(|d| { - let mut v: Vec = d.pattern.clone(); - if v.len() % 2 == 1 { - v.extend_from_within(..); - } - v.iter().map(|x| (x * k).round().clamp(0.0, f64::from(u32::MAX)) as u32).collect() - }); - let native = match (&entries, &p.dash) { - (Some(e), Some(d)) => d.offset.abs() < 1e-9 && e.len() <= MAX_STYLE && e.iter().all(|x| *x >= 1), - _ => true, - }; - let entries = if native { entries.unwrap_or_default() } else { vec![] }; - let cap = match p.cap { - LineCap::Butt => PS_ENDCAP_FLAT, - LineCap::Round => 0, - LineCap::Square => PS_ENDCAP_SQUARE, - }; - let join = match p.join { - LineJoin::Miter => PS_JOIN_MITER, - LineJoin::Round => 0, - LineJoin::Bevel => PS_JOIN_BEVEL, - }; - let style = PS_GEOMETRIC | cap | join | if entries.is_empty() { 0 } else { PS_USERSTYLE }; - let key = PenKey { style, width: (p.width * k).round().clamp(1.0, 1e9) as u32, color: colorref(p.rgb), entries }; - if p.join == LineJoin::Miter { - let m = p.miter.round().clamp(1.0, 1000.0) as u32; - if self.miter != Some(m) { - self.record(SETMITERLIMIT, |o| o.u32(m)); - self.miter = Some(m); - } - } - if self.pen.as_ref() != Some(&key) { - self.drop_pen(); - let n = key.entries.len() as u32; - self.record(EXTCREATEPEN, |o| { - o.u32(PEN); - // No pattern bitmap: its offsets point past the record, its sizes are 0. - let end = 52 + 4 * n; - o.u32(end); - o.u32(0); - o.u32(end); - o.u32(0); - o.u32(key.style); - o.u32(key.width); - // BS_SOLID, the colour, no hatch. - o.u32(0); - o.u32(key.color); - o.u32(0); - o.u32(n); - key.entries.iter().for_each(|e| o.u32(*e)); - }); - self.record(SELECTOBJECT, |o| o.u32(PEN)); - self.pen = Some(key); - } - native - } - - /// `bp` as a path bracket → its device bounds (`None`: nothing to draw). - fn path(&mut self, bp: &BezPath) -> Option { - if !bp.elements().iter().any(|e| !matches!(e, PathEl::MoveTo(_) | PathEl::ClosePath)) { - return None; - } - self.record(BEGINPATH, |_| {}); - let mut bounds: Option = None; - let mut run: Vec<[i32; 2]> = vec![]; - let mut curves = false; - let mut last = Point::ZERO; - let mut start = Point::ZERO; - for el in bp.elements() { - let (pts, is_curve): (Vec, bool) = match *el { - PathEl::MoveTo(p) => { - self.flush_run(&mut run, curves); - let d = self.dev(p); - bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]])); - self.record(MOVETOEX, |o| d.iter().for_each(|v| o.i32(*v))); - (last, start) = (p, p); - continue; - } - PathEl::ClosePath => { - self.flush_run(&mut run, curves); - self.record(CLOSEFIGURE, |_| {}); - last = start; - continue; - } - PathEl::LineTo(p) => (vec![p], false), - PathEl::QuadTo(c, p) => (vec![last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0), p], true), - PathEl::CurveTo(a, b, p) => (vec![a, b, p], true), - }; - if is_curve != curves { - self.flush_run(&mut run, curves); - curves = is_curve; - } - for p in &pts { - let d = self.dev(*p); - bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]])); - run.push(d); - } - last = pts.last().copied().unwrap_or(last); - } - self.flush_run(&mut run, curves); - self.record(ENDPATH, |_| {}); - bounds - } - - /// Write the points of a run of lines or curves, then empty it. - fn flush_run(&mut self, run: &mut Vec<[i32; 2]>, curves: bool) { - if run.is_empty() { - return; - } - let pts = std::mem::take(run); - let b = pts.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]); - self.record(if curves { POLYBEZIERTO } else { POLYLINETO }, |o| { - b.iter().for_each(|v| o.i32(*v)); - o.u32(pts.len() as u32); - for p in &pts { - o.i32(p[0]); - o.i32(p[1]); - } - }); - } - - /// An image placed by `xf` (its pixels → document): StretchDIBits when opaque, else AlphaBlend, - /// drawn at its pixel size under a world transform. - fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) { - if img.width == 0 || img.height == 0 || opacity <= 0.0 { - return; - } - let m = self.to_dev * xf; - if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 { - return; - } - let (w, h) = (f64::from(img.width), f64::from(img.height)); - let corners = [Point::ZERO, Point::new(w, 0.0), Point::new(0.0, h), Point::new(w, h)].map(|p| self.dev(xf * p)); - let b = corners.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]); - self.grow(b); - let [a, bb, c, d, e, f] = m.as_coeffs(); - self.record(SETWORLDTRANSFORM, |o| [a, bb, c, d, e, f].iter().for_each(|v| o.f32(*v as f32))); - let (iw, ih) = (img.width as i32, img.height as i32); - if img.opaque() && opacity >= 0.998 { - let (bmi, bits) = dib::rgb24(img, 1.0); - self.record(STRETCHDIBITS, |o| { - b.iter().for_each(|v| o.i32(*v)); - // Destination and source rectangles. - [0, 0, 0, 0, iw, ih].iter().for_each(|v| o.i32(*v)); - o.u32(80); - o.u32(bmi.len() as u32); - o.u32(80 + bmi.len() as u32); - o.u32(bits.len() as u32); - // DIB_RGB_COLORS, SRCCOPY, the destination size. - o.u32(0); - o.u32(SRCCOPY); - o.i32(iw); - o.i32(ih); - o.bytes(&bmi); - o.bytes(&bits); - }); - } else { - let (bmi, bits) = dib::bgra32(img, opacity); - self.record(ALPHABLEND, |o| { - b.iter().for_each(|v| o.i32(*v)); - [0, 0, iw, ih].iter().for_each(|v| o.i32(*v)); - // AC_SRC_OVER, no flags, constant alpha 255, AC_SRC_ALPHA (per-pixel alpha). - o.bytes(&[0, 0, 255, 1]); - o.i32(0); - o.i32(0); - // The source's own transform: identity. - [1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v)); - o.u32(0); - o.u32(0); - o.u32(108); - o.u32(bmi.len() as u32); - o.u32(108 + bmi.len() as u32); - o.u32(bits.len() as u32); - o.i32(iw); - o.i32(ih); - o.bytes(&bmi); - o.bytes(&bits); - }); - } - // MWT_IDENTITY: back to drawing in device units. - self.record(MODIFYWORLDTRANSFORM, |o| { - [1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v)); - o.u32(1); - }); - } -} diff --git a/crates/metafile/src/encode.rs b/crates/metafile/src/encode.rs new file mode 100644 index 0000000000..6eab34d886 --- /dev/null +++ b/crates/metafile/src/encode.rs @@ -0,0 +1,94 @@ +//! Translate VectorCraft's drawing operations to the shared metafile writers. +use craft_metafile::{ + Cap, Join, + write::{self, Dash, Op, Pen}, +}; +use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::{FillRule, Rect}; + +use crate::{Kind, scene}; + +pub(crate) fn write(ops: Vec, region: Rect, kind: Kind, title: &str, warnings: &mut Vec) -> Result, String> { + let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect(); + let invalid = || "the export region is empty".to_string(); + match kind { + Kind::Emf => write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid), + Kind::Wmf => { + let out = write::wmf(&ops, region).ok_or_else(invalid)?; + for (lost, warning) in [ + (out.translucent_images, "WMF has no transparency: images are written over white"), + (out.turned_images, "WMF can't rotate or skew images: they are written upright, filling their bounds"), + (out.clips_ignored, "clipping masks are not applied: the art they clip is written whole"), + (out.oversized_images, "WMF images with a side over 32,767 pixels were left out"), + ] { + if lost && !warnings.iter().any(|w| w == warning) { + warnings.push(warning.to_string()); + } + } + Ok(out.bytes) + } + } +} + +fn convert(op: scene::Op, kind: Kind) -> Op { + match op { + scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, + scene::Op::Stroke { mut path, pen } => { + let dash = pen.dash.and_then(|dash| { + let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset }; + if kind == Kind::Emf && native.emf_pen_draws() { + Some(native) + } else { + // Keep VectorCraft's own dash placement for strokes that cannot use an + // EMF native pen, including adjusted dashes around corners in WMF. + if let Some(dashed) = vectorcraft_effects::stroke::dash(&path, &dash) { + path = dashed.path; + } + None + } + }); + let cap = match pen.cap { + LineCap::Butt => Cap::Flat, + LineCap::Round => Cap::Round, + LineCap::Square => Cap::Square, + }; + let join = match pen.join { + LineJoin::Miter => Join::Miter, + LineJoin::Round => Join::Round, + LineJoin::Bevel => Join::Bevel, + }; + Op::Stroke { path, pen: Pen { rgb: pen.rgb, width: pen.width, cap, join, miter: pen.miter, dash } } + } + scene::Op::Image { image, xf, opacity } => Op::Image { image, xf, opacity }, + scene::Op::Clip { path, rule } => Op::Clip { path, even_odd: rule == FillRule::EvenOdd }, + scene::Op::Unclip => Op::Unclip, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nonnative_metafile_pens_keep_vectorcraft_corner_alignment() { + let mut path = kurbo::BezPath::new(); + path.move_to((7.0, 8.0)); + path.line_to((42.0, 8.0)); + path.line_to((42.0, 45.0)); + path.line_to((7.0, 45.0)); + path.close_path(); + let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true }; + let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; + let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() }; + let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path; + let region = Rect::new(0.0, 0.0, 50.0, 50.0); + for kind in [Kind::Emf, Kind::Wmf] { + let actual = write(vec![scene::Op::Stroke { path: path.clone(), pen: with_dash.clone() }], region, kind, "", &mut Vec::new()).unwrap(); + let already_dashed = + write(vec![scene::Op::Stroke { path: segments.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap(); + let unsplit = write(vec![scene::Op::Stroke { path: path.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap(); + assert_eq!(actual, already_dashed, "the wire writer must receive the app-aligned segments: {kind:?}"); + assert_ne!(actual, unsplit, "the fixture must distinguish a lost dash pattern: {kind:?}"); + } + } +} diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs index a1e5a674e0..a5ef46316f 100644 --- a/crates/metafile/src/import/pict.rs +++ b/crates/metafile/src/import/pict.rs @@ -206,20 +206,7 @@ fn mix(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] { /// Byte `b` of Mac Roman. fn mac_roman(b: u8) -> char { - const HIGH: [char; 128] = [ - 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // - 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // - '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', // - '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', // - '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', // - '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', // - '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', // - '\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', - ]; - match b { - 0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), - _ => char::from(b), - } + craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b) } /// The family name of a classic Macintosh font number. diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 1cfb3038cd..dab2111119 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -44,9 +44,11 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane}; use crate::dib::Rgba; -use crate::wmf::PLACEABLE_KEY; use crate::{Imported, Kind}; +// The placeable header is interpreted here for VectorCraft’s logical-unit policy. +const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; + const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; const ENDS_EARLY: &str = "the file ends early: what it held was imported"; const TOO_MANY: &str = "objects past the most one file may hold were left out"; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 3f6dd8d5dd..033dc6343a 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -22,18 +22,14 @@ //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! -//! - `bytes`: little-endian writing. -//! - `dib`: device-independent bitmaps for the writers. -//! - `scene`: the document walk both writers share. -//! - `emf`, `wmf`: the writers. -//! - `import`: the readers. +//! The app walks its document and maps its drawing operations to the shared writers. +#[cfg(test)] mod bytes; mod dib; -mod emf; +mod encode; mod import; mod scene; -mod wmf; use vectorcraft_doc::Document; use vectorcraft_geom::Rect; @@ -59,13 +55,10 @@ impl Kind { /// The metafile format `bytes` start like, if any. pub fn sniff(bytes: &[u8]) -> Option { - if emf::is_emf(bytes) { - Some(Kind::Emf) - } else if wmf::is_wmf(bytes) { - Some(Kind::Wmf) - } else { - None - } + craft_metafile::sniff(bytes).map(|kind| match kind { + craft_metafile::Kind::Emf => Kind::Emf, + craft_metafile::Kind::Wmf => Kind::Wmf, + }) } /// A written metafile. @@ -109,18 +102,13 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result emf::write(&ops, r, doc.info_title()), - Kind::Wmf => wmf::write(&ops, r, &mut warnings), - }; - Output { bytes, warnings } + encode::write(ops, r, kind, doc.info_title(), &mut warnings).map(|bytes| Output { bytes, warnings }) }) - .collect(); - Ok(outputs) + .collect() } /// A metafile read into a document. diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index a6c98889f6..3c280822b3 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::{AppearanceItem, Dash, Document, ImageObject, LineCap, Line use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape}; -use crate::dib::Rgba; +use craft_metafile::write::Image; /// How deep symbols, brush art and pattern tiles may nest in one another (deeper art is left out). const MAX_NEST: u32 = 8; @@ -73,7 +73,7 @@ pub(crate) enum Op { /// An image: its pixel space (0..w, 0..h) maps into the document by `xf`; its alpha times /// `opacity`. Image { - image: Arc, + image: Arc, xf: Affine, opacity: f32, }, @@ -104,11 +104,6 @@ fn first_solid(n: &Node) -> Option { own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) } -/// `bp` cut into its dashes (as it is when `dash` draws none), for pens that can't draw them. -pub(crate) fn dashed(bp: &BezPath, dash: Option<&Dash>) -> BezPath { - dash.and_then(|d| stroke::dash(bp, d)).map_or_else(|| bp.clone(), |d| d.path) -} - fn q(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } @@ -124,7 +119,7 @@ pub(crate) struct Scene<'a> { ops: Vec, warnings: Vec, /// Decoded images by key (`None`: can't be decoded, left out). - images: HashMap>>, + images: HashMap>>, brushes: Option>, /// The opacity of the containers around the current object. opacity: f32, @@ -456,7 +451,7 @@ impl<'a> Scene<'a> { }) .collect() }; - let image = Rgba { width: u32::from(cols), height: u32::from(rows), pixels }; + let image = Image { width: u32::from(cols), height: u32::from(rows), rgba: pixels }; let xf = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width() / f64::from(cols), area.height() / f64::from(rows)); self.ops.push(Op::Clip { path: bp.clone(), rule }); @@ -518,7 +513,7 @@ impl<'a> Scene<'a> { /// Image `im`'s pixels (scaled down to what a metafile stores), `None` with a warning when it /// has none or can't be decoded. - fn decoded(&mut self, im: &ImageObject) -> Option> { + fn decoded(&mut self, im: &ImageObject) -> Option> { let key = im.key.as_str(); if let Some(i) = self.images.get(key) { return i.clone(); @@ -527,7 +522,7 @@ impl<'a> Scene<'a> { let img = blob .and_then(|b| craft_image_codecs::decode(&b.bytes).ok()) .and_then(|i| image::RgbaImage::from_raw(i.width(), i.height(), i.to_rgba8())) - .map(Rgba::fitted) + .map(crate::dib::fitted) .filter(|i| i.width > 0 && i.height > 0) .map(Arc::new); if img.is_none() { @@ -541,7 +536,7 @@ impl<'a> Scene<'a> { /// The pixels of `img`, drawn by `xf`, that `clip` (a box in the document) shows, with one pixel /// more on each side: the part and its top left pixel. The whole image when `xf` cannot be /// inverted; `None` when `clip` shows none of it. -fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> { +fn cropped(img: &Image, xf: Affine, clip: Rect) -> Option<(Image, u32, u32)> { if xf.determinant().abs() < 1e-12 || !xf.determinant().is_finite() { return Some((img.clone(), 0, 0)); } @@ -564,9 +559,9 @@ fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> { let mut pixels = Vec::with_capacity((x1 - x0) as usize * (y1 - y0) as usize * 4); for y in y0..y1 { let start = y as usize * row + x0 as usize * 4; - pixels.extend_from_slice(img.pixels.get(start..start + (x1 - x0) as usize * 4)?); + pixels.extend_from_slice(img.rgba.get(start..start + (x1 - x0) as usize * 4)?); } - Some((Rgba { width: x1 - x0, height: y1 - y0, pixels }, x0, y0)) + Some((Image { width: x1 - x0, height: y1 - y0, rgba: pixels }, x0, y0)) } /// Do the instances of `def` stay apart? A grid or brick tiling places its tiles side by side, so diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index d5576ef4b5..eeb30ec846 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -342,7 +342,7 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() { }) .collect(); let (ops, _) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run(); - let parts: Vec<(&crate::dib::Rgba, Affine)> = ops + let parts: Vec<(&craft_metafile::write::Image, Affine)> = ops .iter() .filter_map(|o| match o { crate::scene::Op::Image { image, xf, .. } => Some((&**image, *xf)), @@ -355,12 +355,12 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() { assert!(stored * 4 < 64 * 64 * parts.len() as u64, "{stored} pixels in {} pieces", parts.len()); for ((part, xf), full) in parts.iter().zip(&whole) { // The part's first pixel names where it starts in the image. - let (x0, y0) = (f64::from(part.pixels[0] / 4), f64::from(part.pixels[1] / 4)); + let (x0, y0) = (f64::from(part.rgba[0] / 4), f64::from(part.rgba[1] / 4)); let want = *full * Affine::translate((x0, y0)); assert!(xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{xf:?} against {want:?}"); // Each row runs on from that pixel. let last = (part.width as usize - 1) * 4; - assert_eq!(f64::from(part.pixels[last] / 4), x0 + f64::from(part.width - 1)); + assert_eq!(f64::from(part.rgba[last] / 4), x0 + f64::from(part.width - 1)); } } @@ -394,7 +394,7 @@ fn ruby_is_written_with_its_type() { let reading = contours(&lay.ruby); assert!(reading >= 3, "the reading has ink: {reading}"); let doc = |ruby: bool| doc_with(100.0, 100.0, vec![Node::new(NodeId(0), NodeKind::Text(Box::new(typed(ruby))))]); - let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), crate::emf::MOVETOEX); + let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), 27 /* EMR_MOVETOEX */); assert_eq!(moves(&doc(true)), moves(&doc(false)) + reading, "the reading's contours are written"); assert!(wmf(&doc(true)).bytes.len() > wmf(&doc(false)).bytes.len(), "WMF writes the reading too"); } @@ -411,7 +411,6 @@ fn wmf_placeable_header_checksum_and_record_sizes() { assert_eq!(u16_at(b, 14), 1440); let xor = (0..10).fold(0u16, |a, i| a ^ u16_at(b, 2 * i)); assert_eq!(u16_at(b, 20), xor, "the checksum"); - assert_eq!(crate::wmf::checksum(&b[..20]), xor); // The WMF header: a memory metafile of 9 words, its size in words, the largest record. assert_eq!([u16_at(b, 22), u16_at(b, 24), u16_at(b, 26)], [1, 9, 0x0300]); assert_eq!(u32_at(b, 28) as usize * 2, b.len() - 22); @@ -431,12 +430,12 @@ fn wmf_placeable_header_checksum_and_record_sizes() { #[test] fn wmf_sizes_fit_sixteen_bits() { - assert_eq!(crate::wmf::units_per_inch(612.0, 792.0), 1440); - let inch = crate::wmf::units_per_inch(3000.0, 1000.0); - assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0); + let ordinary = wmf(&doc_with(612.0, 792.0, Vec::new())).bytes; + assert_eq!(u16_at(&ordinary, 14), 1440); let d = doc_with(3000.0, 1000.0, vec![path(shapes::rectangle(Rect::new(0.0, 0.0, 3000.0, 1000.0)), red(), Paint::None, 0.0)]); let b = wmf(&d).bytes; - assert_eq!(u16_at(&b, 14), inch); + let inch = u16_at(&b, 14); + assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0); assert!(u16_at(&b, 10) <= 32767); } @@ -483,10 +482,7 @@ fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run(); - let bytes = match kind { - Kind::Emf => crate::emf::write(&ops, r, doc.info_title()), - Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings), - }; + let bytes = crate::encode::write(ops, r, kind, doc.info_title(), &mut warnings)?; Ok(Output { bytes, warnings }) } diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 217b962dbe..15eca240a9 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -314,7 +314,7 @@ fn hand_wmf(w: i16, h: i16, records: &[(u16, Vec)]) -> Vec { } o.u16(1440); o.u32(0); - let sum = crate::wmf::checksum(&o.0); + let sum = o.0.as_chunks::<2>().0.iter().fold(0, |acc, pair| acc ^ u16::from_le_bytes(*pair)); o.u16(sum); o.bytes(&[1, 0, 9, 0, 0, 3]); o.bytes(&[0; 12]); diff --git a/crates/metafile/src/tests/pict.rs b/crates/metafile/src/tests/pict.rs index 0d8b48c939..54ca33de89 100644 --- a/crates/metafile/src/tests/pict.rs +++ b/crates/metafile/src/tests/pict.rs @@ -236,17 +236,23 @@ fn patterns_fill_with_their_average_color() { #[test] fn text_comes_in_as_point_type_in_the_named_font() { - let name = [be(&[9, 300]), vec![6], b"Geneva".to_vec()].concat(); + let name = [be(&[9, 300]), vec![6], b"Gen\x8Eva".to_vec()].concat(); let bytes = v2( [0, 0, 100, 200], - &[(0x2C, name), (0x03, be(&[300])), (0x0D, be(&[18])), (0x04, vec![1]), (0x28, [be(&[50, 10]), vec![4], b"Caf\x8E".to_vec()].concat())], + &[ + (0x2C, name), + (0x03, be(&[300])), + (0x0D, be(&[18])), + (0x04, vec![1]), + (0x28, [be(&[50, 10]), vec![8], b"Caf\x8E\xCA\xDB\xDE\xF0".to_vec()].concat()), + ], ); let p = import_pict(&bytes).unwrap(); let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect(); let NodeKind::Text(t) = &texts[0].kind else { panic!("text") }; - assert_eq!(t.plain_text(), "Café"); + assert_eq!(t.plain_text(), "Café\u{a0}€fi\u{f8ff}"); let st = &t.runs[0].style; - assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Geneva", "Bold", 18.0)); + assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Genéva", "Bold", 18.0)); // The text location is the baseline's start. assert_eq!(t.xf.translation(), Point::new(10.0, 50.0).to_vec2()); } diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs deleted file mode 100644 index 33a1b081d9..0000000000 --- a/crates/metafile/src/wmf.rs +++ /dev/null @@ -1,441 +0,0 @@ -//! The WMF writer: a placeable header (the picture's size and logical units an inch, with its -//! checksum), the WMF header, then the drawing in 16-bit logical units with an anisotropic window -//! the size of the picture, and the end-of-file record. -//! -//! Curves are flattened into polygons (fills) and polylines (strokes, with pens of the stroke's -//! width, caps and joins; dashes as separate lines). Objects take the lowest free slot of the -//! object table, as players number them: slots 0 and 1 hold a null pen and a null brush, our pen -//! and brush come after and are deleted when replaced. Images are StretchDIB records of 24-bit -//! bitmaps composited over white. - -use kurbo::PathEl; -use vectorcraft_doc::{LineCap, LineJoin}; -use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect}; - -use crate::bytes::Out; -use crate::dib::{self, Rgba}; -use crate::emf::{PS_ENDCAP_FLAT, PS_ENDCAP_SQUARE, PS_JOIN_BEVEL, PS_JOIN_MITER, SRCCOPY, colorref}; -use crate::scene::{Op, Pen}; - -/// The key a placeable header starts with. -pub(crate) const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; - -// Record functions (MS-WMF 2.1.1.1). -pub(crate) const EOF: u16 = 0x0000; -pub(crate) const SETBKMODE: u16 = 0x0102; -pub(crate) const SETMAPMODE: u16 = 0x0103; -pub(crate) const SETPOLYFILLMODE: u16 = 0x0106; -pub(crate) const SETWINDOWORG: u16 = 0x020B; -pub(crate) const SETWINDOWEXT: u16 = 0x020C; -pub(crate) const SELECTOBJECT: u16 = 0x012D; -pub(crate) const DELETEOBJECT: u16 = 0x01F0; -pub(crate) const CREATEPENINDIRECT: u16 = 0x02FA; -pub(crate) const CREATEBRUSHINDIRECT: u16 = 0x02FC; -pub(crate) const POLYGON: u16 = 0x0324; -pub(crate) const POLYLINE: u16 = 0x0325; -pub(crate) const POLYPOLYGON: u16 = 0x0538; -pub(crate) const STRETCHDIB: u16 = 0x0F43; - -/// Most logical units an inch (twips, what office apps use). -const MAX_INCH: f64 = 1440.0; -/// The largest 16-bit coordinate. -const MAX_I16: f64 = 32767.0; -/// Most points a polygon or polyline record holds (its count is 16-bit). -const MAX_POINTS: usize = 32767; -/// Curves are flattened to within this many logical units. -const FLATNESS: f64 = 0.25; -/// The null pen's and the null brush's slots. -const NULL_PEN: u16 = 0; -const NULL_BRUSH: u16 = 1; - -const TRANSLUCENT_IMAGES: &str = "WMF has no transparency: images are written over white"; -const TURNED_IMAGES: &str = "WMF can't rotate or skew images: they are written upright, filling their bounds"; - -/// Does `bytes` start like a WMF (placeable, or a plain memory or disk metafile header)? -pub(crate) fn is_wmf(bytes: &[u8]) -> bool { - let u16_at = |at: usize| bytes.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); - let placeable = bytes.get(..4).is_some_and(|b| b == PLACEABLE_KEY.to_le_bytes()); - placeable || (matches!(u16_at(0), Some(1 | 2)) && u16_at(2) == Some(9) && matches!(u16_at(4), Some(0x0100 | 0x0300))) -} - -/// The logical units an inch for a picture `w` × `h` points: the most, up to 1440, that keep its -/// size within 16 bits. -pub(crate) fn units_per_inch(w: f64, h: f64) -> u16 { - let side_in = w.max(h) / 72.0; - let fit = if side_in > 0.0 { (MAX_I16 / side_in).floor() } else { MAX_INCH }; - fit.clamp(1.0, MAX_INCH) as u16 -} - -/// The XOR of the first ten 16-bit words of a placeable header. -pub(crate) fn checksum(header: &[u8]) -> u16 { - header.as_chunks::<2>().0.iter().take(10).fold(0, |acc, w| acc ^ u16::from_le_bytes(*w)) -} - -/// `bp` flattened to within `tol`: each subpath's points and whether it closes. -fn flatten(bp: &BezPath, tol: f64) -> Vec<(Vec, bool)> { - let mut out: Vec<(Vec, bool)> = vec![]; - let mut cur: Vec = vec![]; - vectorcraft_geom::flatten(bp.iter(), tol, |el| match el { - PathEl::MoveTo(p) => { - if cur.len() > 1 { - out.push((std::mem::take(&mut cur), false)); - } - cur = vec![p]; - } - PathEl::LineTo(p) => cur.push(p), - PathEl::ClosePath => { - if cur.len() > 1 { - out.push((std::mem::take(&mut cur), true)); - } - cur.clear(); - } - _ => {} - }); - if cur.len() > 1 { - out.push((cur, false)); - } - out -} - -/// What a pen object is made of. -#[derive(Clone, Copy, PartialEq)] -struct PenKey { - style: u16, - width: i16, - color: u32, -} - -struct Writer { - /// The records after the headers. - out: Out, - max_record: u32, - to_dev: Affine, - /// Logical units per point. - k: f64, - /// Which object slots are taken. - slots: Vec, - brush: Option<(u16, u32)>, - pen: Option<(u16, PenKey)>, - sel_pen: u16, - sel_brush: u16, - fill_mode: Option, -} - -/// Write `ops` (curves flattened, no clips) as a placeable WMF of `region` (document space). -pub(crate) fn write(ops: &[Op], region: Rect, warnings: &mut Vec) -> Vec { - let inch = units_per_inch(region.width(), region.height()); - let k = f64::from(inch) / 72.0; - let size = |v: f64| (v * k).round().clamp(1.0, MAX_I16) as i16; - let (w, h) = (size(region.width()), size(region.height())); - let mut wr = Writer { - out: Out::default(), - max_record: 0, - to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()), - k, - slots: vec![], - brush: None, - pen: None, - sel_pen: NULL_PEN, - sel_brush: NULL_BRUSH, - fill_mode: None, - }; - // MM_ANISOTROPIC, a window the size of the picture, transparent background. - wr.record(SETMAPMODE, |o| o.u16(8)); - wr.record(SETWINDOWORG, |o| { - o.i16(0); - o.i16(0); - }); - wr.record(SETWINDOWEXT, |o| { - o.i16(h); - o.i16(w); - }); - wr.record(SETBKMODE, |o| o.u16(1)); - // The null pen and brush (slots 0 and 1), selected while ours change. - wr.alloc(); - wr.record(CREATEPENINDIRECT, |o| { - o.u16(5); - o.i16(0); - o.i16(0); - o.u32(0); - }); - wr.alloc(); - wr.record(CREATEBRUSHINDIRECT, |o| { - o.u16(1); - o.u32(0); - o.u16(0); - }); - wr.select(NULL_PEN); - wr.select(NULL_BRUSH); - let mut translucent = false; - let mut turned = false; - for op in ops { - match op { - Op::Fill { path, rule, rgb } => wr.fill(path, *rule, *rgb), - Op::Stroke { path, pen } => wr.stroke(path, pen), - Op::Image { image, xf, opacity } => { - translucent |= !image.opaque() || *opacity < 0.998; - turned |= !wr.image(image, *xf, *opacity); - } - // The scene gives formats without clipping none. - Op::Clip { .. } | Op::Unclip => {} - } - } - if let Some((slot, _)) = wr.brush.take() { - wr.select(NULL_BRUSH); - wr.delete(slot); - } - if let Some((slot, _)) = wr.pen.take() { - wr.select(NULL_PEN); - wr.delete(slot); - } - wr.record(EOF, |_| {}); - for (on, w) in [(translucent, TRANSLUCENT_IMAGES), (turned, TURNED_IMAGES)] { - if on && !warnings.iter().any(|x| x == w) { - warnings.push(w.to_string()); - } - } - wr.finish(w, h, inch) -} - -impl Writer { - /// Append one record: its size in 16-bit words, its function and `body`. - fn record(&mut self, function: u16, body: impl FnOnce(&mut Out)) { - let start = self.out.len(); - self.out.u32(0); - self.out.u16(function); - body(&mut self.out); - self.out.pad(2); - let words = u32::try_from((self.out.len() - start) / 2).unwrap_or(u32::MAX); - self.out.set_u32(start, words); - self.max_record = self.max_record.max(words); - } - - /// The placeable header, the WMF header, then the records. - fn finish(self, w: i16, h: i16, inch: u16) -> Vec { - let mut o = Out::default(); - o.u32(PLACEABLE_KEY); - o.u16(0); - for v in [0, 0, w, h] { - o.i16(v); - } - o.u16(inch); - o.u32(0); - let sum = checksum(&o.0); - o.u16(sum); - // A memory metafile, 9 words of header, version 3. - o.u16(1); - o.u16(9); - o.u16(0x0300); - o.u32(u32::try_from((18 + self.out.len()) / 2).unwrap_or(u32::MAX)); - o.u16(u16::try_from(self.slots.len()).unwrap_or(u16::MAX)); - o.u32(self.max_record); - o.u16(0); - o.bytes(&self.out.0); - o.0 - } - - /// The lowest free object slot, taken. - fn alloc(&mut self) -> u16 { - let i = match self.slots.iter().position(|t| !t) { - Some(i) => i, - None => { - self.slots.push(false); - self.slots.len() - 1 - } - }; - if let Some(s) = self.slots.get_mut(i) { - *s = true; - } - u16::try_from(i).unwrap_or(u16::MAX) - } - - fn select(&mut self, slot: u16) { - self.record(SELECTOBJECT, |o| o.u16(slot)); - } - - fn delete(&mut self, slot: u16) { - self.record(DELETEOBJECT, |o| o.u16(slot)); - if let Some(s) = self.slots.get_mut(usize::from(slot)) { - *s = false; - } - } - - fn dev(&self, p: Point) -> [i16; 2] { - let q = self.to_dev * p; - let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_I16, MAX_I16) as i16 } else { 0 }; - [c(q.x), c(q.y)] - } - - /// The device points of `pts`, repeats dropped, thinned to what one record holds. - fn points(&self, pts: &[Point]) -> Vec<[i16; 2]> { - let mut v: Vec<[i16; 2]> = vec![]; - for p in pts { - let d = self.dev(*p); - if v.last() != Some(&d) { - v.push(d); - } - } - if v.len() > MAX_POINTS { - let step = v.len().div_ceil(MAX_POINTS - 1); - let last = v.last().copied(); - v = v.into_iter().step_by(step).collect(); - v.extend(last); - } - v - } - - fn select_pen(&mut self, slot: u16) { - if self.sel_pen != slot { - self.select(slot); - self.sel_pen = slot; - } - } - - fn select_brush(&mut self, slot: u16) { - if self.sel_brush != slot { - self.select(slot); - self.sel_brush = slot; - } - } - - fn use_brush(&mut self, rgb: [u8; 3]) { - let color = colorref(rgb); - let slot = match self.brush { - Some((slot, c)) if c == color => slot, - old => { - if let Some((slot, _)) = old { - self.select_brush(NULL_BRUSH); - self.delete(slot); - } - let slot = self.alloc(); - self.record(CREATEBRUSHINDIRECT, |o| { - o.u16(0); - o.u32(color); - o.u16(0); - }); - self.brush = Some((slot, color)); - slot - } - }; - self.select_brush(slot); - } - - fn use_pen(&mut self, p: &Pen) { - let cap = match p.cap { - LineCap::Butt => PS_ENDCAP_FLAT, - LineCap::Round => 0, - LineCap::Square => PS_ENDCAP_SQUARE, - }; - let join = match p.join { - LineJoin::Miter => PS_JOIN_MITER, - LineJoin::Round => 0, - LineJoin::Bevel => PS_JOIN_BEVEL, - }; - let key = PenKey { style: (cap | join) as u16, width: (p.width * self.k).round().clamp(1.0, MAX_I16) as i16, color: colorref(p.rgb) }; - let slot = match self.pen { - Some((slot, k)) if k == key => slot, - old => { - if let Some((slot, _)) = old { - self.select_pen(NULL_PEN); - self.delete(slot); - } - let slot = self.alloc(); - self.record(CREATEPENINDIRECT, |o| { - o.u16(key.style); - o.i16(key.width); - o.i16(0); - o.u32(key.color); - }); - self.pen = Some((slot, key)); - slot - } - }; - self.select_pen(slot); - } - - fn fill(&mut self, bp: &BezPath, rule: FillRule, rgb: [u8; 3]) { - let polys: Vec> = flatten(bp, FLATNESS / self.k).iter().map(|(p, _)| self.points(p)).filter(|p| p.len() > 2).collect(); - if polys.is_empty() { - return; - } - // ALTERNATE (even-odd) or WINDING (non-zero). - let mode = if rule == FillRule::EvenOdd { 1 } else { 2 }; - if self.fill_mode != Some(mode) { - self.record(SETPOLYFILLMODE, |o| o.u16(mode)); - self.fill_mode = Some(mode); - } - self.use_brush(rgb); - self.select_pen(NULL_PEN); - for chunk in polys.chunks(usize::from(u16::MAX)) { - self.record(POLYPOLYGON, |o| { - o.u16(chunk.len() as u16); - chunk.iter().for_each(|p| o.u16(p.len() as u16)); - for p in chunk.iter().flatten() { - o.i16(p[0]); - o.i16(p[1]); - } - }); - } - } - - fn stroke(&mut self, bp: &BezPath, pen: &Pen) { - let path = crate::scene::dashed(bp, pen.dash.as_ref()); - let lines: Vec<(Vec<[i16; 2]>, bool)> = - flatten(&path, FLATNESS / self.k).iter().map(|(p, closed)| (self.points(p), *closed)).filter(|(p, _)| p.len() > 1).collect(); - if lines.is_empty() { - return; - } - self.use_pen(pen); - self.select_brush(NULL_BRUSH); - for (pts, closed) in lines { - // A closed subpath is a polygon (with the null brush, its outline), so it joins at - // its start. - self.record(if closed { POLYGON } else { POLYLINE }, |o| { - o.i16(pts.len() as i16); - for p in &pts { - o.i16(p[0]); - o.i16(p[1]); - } - }); - } - } - - /// An image placed by `xf`, upright: false when `xf` rotates or skews it (then it fills its - /// bounds). - fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) -> bool { - if img.width == 0 || img.height == 0 || opacity <= 0.0 { - return true; - } - let m = self.to_dev * xf; - if !m.as_coeffs().iter().all(|v| v.is_finite()) { - return true; - } - let [a, b, c, d, e, f] = m.as_coeffs(); - let (w, h) = (f64::from(img.width), f64::from(img.height)); - let upright = b.abs() < 1e-9 && c.abs() < 1e-9; - let (x, y, dw, dh) = if upright { - (e, f, a * w, d * h) - } else { - let r = m.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)); - (r.x0, r.y0, r.width(), r.height()) - }; - let s = |v: f64| v.round().clamp(-MAX_I16, MAX_I16) as i16; - let (bmi, bits) = dib::rgb24(img, opacity); - self.record(STRETCHDIB, |o| { - o.u32(SRCCOPY); - // DIB_RGB_COLORS; the source and destination rectangles, last field first. - o.u16(0); - o.i16(img.height as i16); - o.i16(img.width as i16); - o.i16(0); - o.i16(0); - o.i16(s(dh)); - o.i16(s(dw)); - o.i16(s(y)); - o.i16(s(x)); - o.bytes(&bmi); - o.bytes(&bits); - }); - upright - } -} diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index 655e84e311..e10d8df5b7 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -576,15 +576,13 @@ fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result, s: f64, k: usize, lo: f64, hi: f64| { - let g = |t: f64| f(t, k); + // Between `lo` and `hi`, where `s * g` is positive at both ends: the least of `s * g`, a double + // root where it reaches zero, two roots where it goes past it, none where it stays above. + let dip = |out: &mut Vec, s: f64, g: &dyn Fn(f64) -> f64, lo: f64, hi: f64| { let (t, least) = golden(&|t| s * g(t), lo, hi); if least < -tol { - out.push(simple(bisect(&g, lo, t))); - out.push(simple(bisect(&g, t, hi))); + out.push(simple(bisect(g, lo, t))); + out.push(simple(bisect(g, t, hi))); } else if least <= tol { out.push(Root { angle: t, double: true }); } @@ -604,12 +602,47 @@ fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result = (1..=len + 1).map(|j| ang(k, j)).collect(); + let piece = |t: f64| { + let j = edges.partition_point(|a| *a <= t); + f(t, (k + j) % n) + }; + let mut marks = vec![(theta, val(k))]; + for j in 1..len { + let (lo, hi) = (ang(k, j), ang(k, j + 1)); + let g = |t: f64| f(t, (k + j) % n); + let (t_low, low) = golden(&g, lo, hi); + let (t_high, high) = golden(&|t| -g(t), lo, hi); + let mut found: Vec<(f64, f64)> = [(t_low, low), (t_high, -high)].into_iter().filter(|(_, v)| !zero(*v)).collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + marks.extend(found); + } + marks.push((ang(k, len + 1), val(k + len + 1))); + if marks.len() == 2 { + out.push(Root { angle: (ang(k, 1) + ang(k, len)) / 2.0, double: true }); + } else { + for pair in marks.windows(2) { + if let [(lo, a), (hi, b)] = *pair { + if a.signum() == b.signum() { + dip(&mut out, a.signum(), &piece, lo, hi); + } else { + out.push(simple(bisect(&piece, lo, hi))); + } + } + } + } } continue; } @@ -622,7 +655,7 @@ fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result = out.into_iter().map(|r| Root { angle: r.angle.rem_euclid(TAU), ..r }).collect(); @@ -1135,6 +1168,22 @@ mod tests { assert_eq!(at(1e-6).len(), 2); } + #[test] + fn a_point_whose_two_tangents_fall_on_neighboring_samples_keeps_both() { + // The point lies on the bisector of two neighboring sampled normals, at the distance where + // its two tangents touch the circle at exactly those normals. Both samples are zero, but + // between them the point is well outside the circle: two lines, not one. + let (r, half) = (10.0, TAU / SAMPLES as f64 / 2.0); + let p = (Vec2::new(half.cos(), half.sin()) * (r / half.cos())).to_point(); + let all = common_tangents(&Outline::point(p).unwrap(), &circle(0.0, 0.0, r)).unwrap(); + assert_eq!(all.len(), 2, "{all:?}"); + // Each runs from the point to where the circle's radius meets it square. + for angle in [0.0, 2.0 * half] { + let touch = (Vec2::new(angle.cos(), angle.sin()) * r).to_point(); + assert!(all.iter().any(|t| ends_within(t, p, touch, 1e-6)), "{angle}: {all:?}"); + } + } + #[test] fn open_concave_empty_and_identical_outlines_are_refused() { let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false); diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 3ad1281eb2..c5a340365a 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -1,7 +1,8 @@ //! Object → Path commands: Simplify, Smooth, Remove redundant points, Add Anchor Points, Average, //! Join, Split Into Grid. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::ops::Range; use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; @@ -97,7 +98,10 @@ fn turn_deg(a: &Seg, b: &Seg) -> f64 { d.acos().to_degrees() } -/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. +/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. A closed +/// subpath starts where it did: at its first anchor when the refit keeps an anchor there, otherwise +/// at a new anchor split into the refit at its point nearest there when the refit still has fewer +/// anchors than the subpath with that one, and otherwise at the refit's anchor nearest there. pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { let mut out = Vec::new(); for sp in &path.subpaths { @@ -108,15 +112,151 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { PathData::new(out) } -/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed subpath -/// whose refit is one segment, or lines that enclose no area, is refitted in two parts, cut at the -/// point farthest from its start, or in three when two still give that. When three parts still give -/// no area, straight lines follow the subpath within the tolerance, and without straight lines it +/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed refit +/// starts where the subpath started ([`keep_start`]). +fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { + refit_subpath(sp, opts).map(|fit| { + let n = fit.anchors.len(); + keep_start(fit, sp, 0..n).0 + }) +} + +/// Distance (points) from an anchor within which a closed path restarted by [`start_nearest`] +/// starts at that anchor instead of at a new one split in beside it. +pub const START_SNAP: f64 = 1e-3; + +/// Distance (points) within which two points of a closed path count as equally near its old start. +const START_TIE: f64 = 1e-6; + +/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of +/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place +/// when there is none. +fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { + #[cfg(test)] + tests::count_places(); + let mut best: Option<(f64, usize, f64)> = None; + for j in 0..orig.anchors.len() { + let hit = orig.segment(j).nearest(p, 1e-9); + if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { + best = Some((hit.distance_sq, j, hit.t)); + } + } + best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) +} + +/// Of the candidates (distance, point, value), the value of the nearest, with a finite distance: +/// of those within [`START_TIE`] of each other, the one whose point is earliest along `orig` from +/// its first anchor, then the first given. Each distinct point is placed along `orig` once. +fn earliest_nearest(candidates: impl IntoIterator, orig: &SubPath) -> Option { + // (distance, place along `orig` once a tie needs it, point, value) + type Best = (f64, Option<(usize, f64)>, Point, T); + let mut best: Option> = None; + // Places along `orig` by the bits of the point, so many ties at one point search `orig` once. + let mut placed: HashMap<[u64; 2], (usize, f64)> = HashMap::new(); + let mut place = |p: Point| *placed.entry([p.x.to_bits(), p.y.to_bits()]).or_insert_with(|| place_along(orig, p)); + for (d, p, x) in candidates { + if !d.is_finite() { + continue; + } + match &mut best { + None => best = Some((d, None, p, x)), + Some((bd, bplace, bp, _)) if (d - *bd).abs() <= START_TIE => { + let held = *bplace.get_or_insert_with(|| place(*bp)); + let at = place(p); + if at.0 < held.0 || (at.0 == held.0 && at.1 < held.1) { + best = Some((d, Some(at), p, x)); + } + } + Some((bd, ..)) if d < *bd => best = Some((d, None, p, x)), + Some(_) => {} + } + } + best.map(|(.., x)| x) +} + +/// The closed `sp` started at the point on it nearest `start`: at an anchor within [`START_SNAP`] of +/// `start` when it has one, even where a segment crosses the path there, otherwise at the anchor at +/// that point or at a new anchor split into the segment there, which leaves the outline as it is. Of +/// points equally near `start`, the one earliest along `orig` (the path before it was refitted) from +/// its first anchor is used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest +/// point, is returned as it is. +pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { + let n = sp.anchors.len(); + start_near(sp, start, orig, true, 0..n).0 +} + +/// [`start_nearest`] on the segments `within` alone, splitting a segment only when `split` is set; +/// otherwise, when no anchor lies at the nearest point, the path starts at the anchor of those +/// segments nearest `start`, with the same tie rule. → (the path, the segment split when one was, +/// where the new start was before the anchors turned). +fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within: Range) -> (SubPath, Option, usize) { + let n = sp.anchors.len(); + if !sp.closed || n < 2 { + return (sp, None, 0); + } + let within = within.start.min(n)..within.end.min(n); + // The anchors of the segments `within`: each one's first, and the last one's end. + let anchors = || (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); + // An anchor within [`START_SNAP`] of `start` starts the path, before any segment through there. + let snapped = if within.is_empty() { None } else { earliest_nearest(anchors().filter(|(d, ..)| *d <= START_SNAP), orig) }; + if let Some(first) = snapped { + sp.anchors.rotate_left(first); + return (sp, None, first); + } + let hits = within.clone().map(|i| { + let c = sp.segment(i); + let hit = c.nearest(start, 1e-9); + let d = if hit.distance_sq.is_finite() && hit.t.is_finite() { hit.distance_sq.sqrt() } else { f64::NAN }; + (d, c.eval(hit.t), (i, hit.t)) + }); + let Some((i, t)) = earliest_nearest(hits, orig) else { return (sp, None, 0) }; + let c = sp.segment(i); + let at = c.eval(t); + let (first, cut) = if at.distance(c.p0) <= START_SNAP { + (i, None) + } else if at.distance(c.p3) <= START_SNAP { + ((i + 1) % n, None) + } else if split { + let mid = if sp.segment_is_line(i) { + Anchor::corner(at) + } else { + let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); + sp.anchors[i].h_out = l.p1; + sp.anchors[(i + 1) % n].h_in = r.p2; + Anchor::with_handles(at, l.p2, r.p1) + }; + sp.anchors.insert(i + 1, mid); + (i + 1, Some(i)) + } else { + (earliest_nearest(anchors(), orig).unwrap_or(0), None) + }; + sp.anchors.rotate_left(first); + (sp, cut, first) +} + +/// The closed refit `fit` of the closed `orig` started where `orig` starts: at its anchor at +/// `orig`'s first anchor, or at a new anchor split in at its point nearest there when it still has +/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]), +/// looking only at the segments `within`. An open `orig` keeps `fit` as it is. +fn keep_start(fit: SubPath, orig: &SubPath, within: Range) -> (SubPath, Option, usize) { + match orig.anchors.first() { + Some(a) if orig.closed => { + let split = fit.anchors.len() + 1 < orig.anchors.len(); + start_near(fit, a.p, orig, split, within) + } + _ => (fit, None, 0), + } +} + +/// [`simplify_subpath`] before the start is put back: a closed subpath whose refit is one segment, +/// or lines that enclose no area, is refitted in two parts, cut at the point farthest from its +/// start, or in three when two still give that. When three parts still give no area, straight lines +/// follow the subpath within the tolerance, and without straight lines it /// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose /// an area, it stays as it is, or with straight lines follows the lines between samples of each /// curved segment when the limits leave room for lines within the tolerance; one that is all in line /// keeps the refit. -fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { +fn refit_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); if n == 0 || sp.closed && n < 2 { @@ -694,7 +834,9 @@ pub struct SimplifiedPart { /// two end anchors, which stay where they are with their handles on the side away from the run. /// The other segments and anchors stay exactly as they are. A subpath whose every segment is in /// `segments` is simplified whole, as [`simplify_with`] does. A run whose refit would have more -/// segments than it had is left as it is (except with Convert to Straight Lines). +/// segments than it had is left as it is (except with Convert to Straight Lines). A closed subpath +/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]), on the run that held its +/// first anchor when that anchor goes. pub fn simplify_part(path: &PathData, segments: &BTreeSet<(usize, usize)>, opts: &SimplifyOptions) -> SimplifiedPart { let opts = &SimplifyOptions { free_start: false, free_end: false, ..*opts }; let (mut runs, mut anchors) = (BTreeSet::new(), BTreeMap::new()); @@ -733,6 +875,7 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP let mut anchors = vec![sp.anchors[start]]; let mut kept = vec![(start, 0)]; let mut runs = vec![]; + let mut start_run = None; let mut k = 0; while k < n { let j = (start + k) % n; @@ -765,7 +908,12 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } // The run's segments, from its first anchor on: a run back to the walk's start ends with // the closing segment, the last index. - runs.extend(first..first + if keep_original { run.len() } else { fitted.len() }); + let segs = first..first + if keep_original { run.len() } else { fitted.len() }; + if sp.closed && (k + 1..k + len).any(|i| (start + i) % m == 0) { + // The run that held the old first anchor. + start_run = Some(segs.clone()); + } + runs.extend(segs); let end_seg = fitted.last().filter(|_| !keep_original); if sp.closed && k + len == n { // The run ends where the walk started. @@ -782,7 +930,20 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } k += len; } - (SubPath::new(anchors, sp.closed), runs, kept) + // A closed subpath starts where it did: the walk already starts at its first anchor when that + // stays, and otherwise the run that held it starts the path ([`keep_start`] on that run's + // segments alone, so no other segment changes), with the runs and anchors kept renumbered. + let Some(within) = start_run else { return (SubPath::new(anchors, sp.closed), runs, kept) }; + let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp, within); + let len = out.anchors.len(); + if (cut, first) == (None, 0) || len == 0 { + return (out, runs, kept); + } + let turned = |i: usize| (i + len - first) % len; + let after_cut = |i: usize| i + usize::from(cut.is_some_and(|c| i > c)); + let runs = runs.into_iter().flat_map(|s| if cut == Some(s) { vec![s, s + 1] } else { vec![after_cut(s)] }).map(turned).collect(); + let kept = kept.into_iter().map(|(old, new)| (old, turned(after_cut(new)))).collect(); + (out, runs, kept) } /// `a` with its out (`out`) or in handle at `h` and the other as it is: still smooth when it was @@ -1402,6 +1563,102 @@ mod tests { MOVES.set(MOVES.get() + n); } + std::thread_local! { + /// Calls of [`place_along`], each a search of every segment of the path before the refit. + static PLACES: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub(super) fn count_places() { + PLACES.set(PLACES.get() + 1); + } + + /// A refitted run across the start of a closed path that crosses itself at its start keeps the + /// start on the run: the unselected segment through the old start is not split. + #[test] + fn a_run_across_the_start_keeps_the_start_on_the_run() { + let pts = [ + (0.0, 0.0), + (10.0, 0.3), + (20.0, -0.3), + (30.0, 0.3), + (40.0, 0.6), + (40.0, 50.0), + (0.0, 50.0), + (0.0, -50.0), + (-40.0, -50.0), + (-40.0, 0.6), + (-30.0, 0.3), + (-20.0, -0.3), + (-10.0, 0.3), + ]; + let sp = SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true); + let path = PathData::new(vec![sp]); + let picked: BTreeSet<(usize, usize)> = [9, 10, 11, 12, 0, 1, 2, 3].into_iter().map(|s| (0, s)).collect(); + let out = simplify_part(&path, &picked, &SimplifyOptions { tolerance: 1.0, ..SimplifyOptions::default() }); + let got = &out.path.subpaths[0]; + let n = got.anchors.len(); + assert!(n < pts.len(), "{n} anchors"); + let (top, bottom) = (Point::new(0.0, 50.0), Point::new(0.0, -50.0)); + assert!( + (0..n).any(|i| got.anchors[i].p == top && got.anchors[(i + 1) % n].p == bottom), + "the segment through the old start was split: {:?}", + got.anchors.iter().map(|a| a.p).collect::>() + ); + assert!(got.anchors[0].p.x.abs() < 40.0 && got.anchors[0].p.y.abs() <= 1.0, "start {:?}", got.anchors[0].p); + } + + /// A closed polyline from its start at (0, 0) up to (0, 10) whose diagonal from (-20, -20) to + /// (20, 20) crosses it at that start, with two anchors on the diagonal that a refit drops. + fn crossing_at_start() -> SubPath { + let pts = [(0, 0), (0, 10), (40, 10), (40, -20), (-20, -20), (-10, -10), (10, 10), (20, 20), (20, 30), (-10, 30), (-10, 0)]; + SubPath::polyline(&pts.map(|(x, y)| Point::new(f64::from(x), f64::from(y))), true) + } + + /// A refitted run that keeps an anchor at the old start of a closed path starts the path at that + /// anchor, though a segment of the run that crosses the path there comes first in the run. + #[test] + fn a_run_that_keeps_the_start_anchor_starts_there() { + let path = PathData::new(vec![crossing_at_start()]); + let picked: BTreeSet<(usize, usize)> = [0, 4, 5, 6, 7, 8, 9, 10].into_iter().map(|s| (0, s)).collect(); + let opts = SimplifyOptions { tolerance: 0.01, corner_angle_deg: 1.0, straight_lines: true, ..SimplifyOptions::default() }; + let got = &simplify_part(&path, &picked, &opts).path.subpaths[0]; + let ps: Vec = got.anchors.iter().map(|a| a.p).collect(); + assert_eq!(ps.len(), 9, "{ps:?}"); + assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}"); + assert_eq!(ps.iter().filter(|&&p| p == Point::ZERO).count(), 1, "{ps:?}"); + } + + /// The whole closed path refitted keeps its start anchor first when a segment of the refit + /// crosses the path there. + #[test] + fn a_refit_that_keeps_the_start_anchor_starts_there() { + let sp = crossing_at_start(); + let mut fit = sp.clone(); + fit.anchors.retain(|a| ![Point::new(-10.0, -10.0), Point::new(10.0, 10.0)].contains(&a.p)); + fit.anchors.rotate_left(4); + let n = fit.anchors.len(); + let (got, cut, _) = keep_start(fit, &sp, 0..n); + let ps: Vec = got.anchors.iter().map(|a| a.p).collect(); + assert_eq!(cut, None, "{ps:?}"); + assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}"); + } + + /// Candidates tied at one point are placed along the old path once, not once each, and the first + /// given still wins the tie. + #[test] + fn tied_candidates_at_one_point_are_placed_once() { + let orig = SubPath::new( + vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 0.0)), Anchor::corner(Point::new(100.0, 100.0))], + true, + ); + let candidates = (0..1000).map(|i| (0.0, Point::new(0.0, 0.0), i)); + PLACES.set(0); + let got = earliest_nearest(candidates, &orig); + let places = PLACES.get(); + assert_eq!(got, Some(0)); + assert_eq!(places, 1, "searches of the old path for 1000 candidates at one point"); + } + /// A subpath of `n` anchors from `seed`: corners, smooth points and points with one handle. fn random_subpath(seed: &mut u64, n: usize, closed: bool) -> SubPath { let mut rnd = || { diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d500182401..0ff1b82594 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -22,9 +22,9 @@ pub use boolean::{ try_unite_all_with, unite_all, unite_all_with, }; pub use edit::{ - AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, - remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, - smooth_options, split_into_grid, + AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, START_SNAP, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, + join, remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, + smooth_level, smooth_options, split_into_grid, start_nearest, }; pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index a31c9af2e4..60410a0d5d 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -742,6 +742,74 @@ fn smooth_level_0_keeps_a_closed_paths_start_corner_within_tolerance() { assert!(moved <= limit, "level 0 moved the path by {moved} pt, more than {limit} pt: {:?}", s.subpaths[0].anchors[0]); } +/// Twice the area `sp` encloses, from 16 points along each segment: positive when it runs +/// counterclockwise in y-up terms. +fn signed_area(sp: &SubPath) -> f64 { + let pts: Vec = (0..sp.segment_count()).flat_map(|i| (0..16).map(move |k| sp.segment(i).eval(f64::from(k) / 16.0))).collect(); + (0..pts.len()).map(|i| pts[i].to_vec2().cross(pts[(i + 1) % pts.len()].to_vec2())).sum() +} + +/// A D of 41 corner points round (0, 0): the arc of radius 100 from (100, 0) up to (0, 100), the +/// straight side down to (0, -100), and the arc back. It starts in the middle of its arc, and its +/// first corner is at the top. +fn d_shape() -> SubPath { + let at = |deg: f64| Point::new(100.0 * deg.to_radians().cos(), 100.0 * deg.to_radians().sin()); + let pts: Vec = (0..=20).map(|i| at(4.5 * f64::from(i))).chain((0..20).map(|i| at(-90.0 + 4.5 * f64::from(i)))).collect(); + SubPath::polyline(&pts, true) +} + +/// Object › Path › Simplify starts a closed path where it started, though the refit runs from the +/// first corner: on the D, the refit starts within the tolerance of the old start, runs the same way +/// round, and has fewer anchors. +#[test] +fn simplify_keeps_a_closed_paths_start() { + let sp = d_shape(); + let path = PathData::single(sp.clone()); + let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, ..Default::default() }); + let out = &s.subpaths[0]; + assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}"); + let moved = out.anchors[0].p.distance(sp.anchors[0].p); + assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt, to {:?}", out.anchors[0].p); + assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays"); + assert!(one_way_distance(&path, &s).max(one_way_distance(&s, &path)) <= 1.0 + 1e-6); +} + +/// Object › Path › Smooth starts a closed path near where it started, though the refit runs from the +/// point where the path turns back: a round loop of radius 50 with a needle out to (250, 0), which +/// starts on the far side of the loop at (-50, 0). +#[test] +fn smooth_keeps_a_closed_paths_start() { + let at = |deg: f64| Point::new(50.0 * deg.to_radians().cos(), 50.0 * deg.to_radians().sin()); + let pts: Vec = (0..=20) + .map(|i| at(180.0 + 8.95 * f64::from(i))) + .chain([Point::new(250.0, 0.0)]) + .chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))) + .collect(); + let sp = SubPath::polyline(&pts, true); + let path = PathData::single(sp.clone()); + let s = smooth_level(&path, SMOOTH_AUTO_LEVEL); + let out = &s.subpaths[0]; + assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}"); + let moved = out.anchors[0].p.distance(sp.anchors[0].p); + assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", out.anchors[0].p); + assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays"); +} + +/// A refit with only one anchor fewer than the closed path gets no anchor split in to keep its +/// start: it starts at its anchor nearest the old start. A rectangle with a straight point at +/// (30, 0) simplifies to its four corners, starting at (0, 0). +#[test] +fn simplify_starts_at_the_nearest_anchor_rather_than_add_one_back() { + let pts = [(30.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)); + let path = PathData::single(SubPath::polyline(&pts, true)); + let want = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(|(x, y)| Point::new(x, y)); + for straight_lines in [false, true] { + let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, straight_lines, ..Default::default() }); + let got: Vec = s.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(got, want, "straight_lines {straight_lines}"); + } +} + #[test] fn remove_redundant_collinear_and_curve() { let p = PathData::single(SubPath::polyline( diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 3da2079b9b..dfaf9a2c7c 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -183,22 +183,33 @@ impl Exporter<'_> { /// CMYK image `im` with the alpha of its opacity mask `m`, when the mask is a greyscale image /// on the image's own pixel grid (an image's soft mask as it opens): the alpha is written as the /// image's soft mask, as an RGBA image's is, rather than as a luminosity soft mask over it, - /// through which CoreGraphics draws CMYK images on black boxes (#2159). `None` for other - /// images and masks; cached like [`Self::load_image`], `interpolate` as there. - pub(super) fn masked_image(&mut self, im: &vectorcraft_doc::ImageObject, m: &vectorcraft_doc::OpacityMask, interpolate: bool) -> Option { + /// through which CoreGraphics draws CMYK images on black boxes (#2159). `shown` is `im` as it is + /// shown ([`vectorcraft_doc::Document::shown_image`]). When a color mask shows other pixels + /// that are not CMYK (`im`'s own pixels with the hidden colors clear), `im`'s inks are written + /// with the mask's alpha multiplied by the shown pixels' alpha, so the hidden colors stay + /// hidden; shown pixels that are CMYK are written themselves. `None` for other images and + /// masks, and for shown pixels of another size; cached like [`Self::load_image`], + /// `interpolate` as there. + pub(super) fn masked_image( + &mut self, + im: &vectorcraft_doc::ImageObject, + shown: &vectorcraft_doc::ImageObject, + m: &vectorcraft_doc::OpacityMask, + interpolate: bool, + ) -> Option { let art = &m.art; let NodeKind::Image(mi) = &art.kind else { return None }; // A color-masked image in the mask's art masks with the pixels it shows. - let shown = self.doc.shown_image(art, mi); - let mi = &*shown; + let shown_mask = self.doc.shown_image(art, mi); + let mi = &*shown_mask; let plain = art.opacity >= 1.0 && art.blend == BlendMode::Normal && art.extras().mask.is_none() && !art.appearance.effects.iter().any(|e| e.visible); if m.invert || !plain || (mi.xf, mi.width, mi.height) != (im.xf, im.width, im.height) { return None; } - let size = self.image_size(im); + let size = self.image_size(shown); let interpolate = interpolate && self.interpolate; - let mut cache = format!("{}\u{0}{}\u{0}{}", im.key, mi.key, m.clip); + let mut cache = format!("{}\u{0}{}\u{0}{}\u{0}{}", im.key, shown.key, mi.key, m.clip); if self.downsampled() { cache.push_str(&format!("\u{0}{:.3}x{:.3}", size.0, size.1)); } @@ -209,8 +220,20 @@ impl Exporter<'_> { return i.clone(); } let doc = self.doc; - let img = doc.image_blob(im).filter(|b| b.is_cmyk()).and_then(|blob| { - let alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?; + // Pixels a color mask shows that are not CMYK carry the hidden colors as their alpha. + let shown_blob = doc.image_blob(shown); + let (source, hidden) = match shown_blob { + Some(b) if shown.key != im.key && !b.is_cmyk() => (doc.image_blob(im), Some(b)), + b => (b, None), + }; + let img = source.filter(|b| b.is_cmyk()).and_then(|blob| { + let mut alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?; + if let Some(hidden) = hidden { + let shown_alpha = crate::images::image_alpha(hidden, im.width, im.height)?; + for (a, s) in alpha.iter_mut().zip(shown_alpha) { + *a = ((u32::from(*a) * u32::from(s) + 127) / 255) as u8; + } + } let icc = self.out.cmyk_image_icc(blob); let tag = self.out.cmyk_tag(icc.as_deref()); let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), tag); @@ -452,7 +475,8 @@ mod tests { assert!(exporter.colorized_image(&image("pic", scale), &paint, true).is_some(), "colorized at {scale}"); let art = vectorcraft_doc::Node::new(doc.layers[0].id, vectorcraft_doc::NodeKind::Image(Box::new(image("alpha", scale)))); let mask = vectorcraft_doc::OpacityMask::new(art, true); - assert!(exporter.masked_image(&image("inks", scale), &mask, true).is_some(), "masked at {scale}"); + let inks = image("inks", scale); + assert!(exporter.masked_image(&inks, &inks, &mask, true).is_some(), "masked at {scale}"); } assert_eq!(exporter.images.len(), 2, "{:?}", exporter.images.keys().collect::>()); } diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 94b1c819c5..d84e8f7124 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -375,7 +375,11 @@ impl Exporter<'_> { let mask = n.extras().mask.as_deref().filter(|m| !m.disabled); let alpha = match (&n.kind, mask) { // The mask's image shares the pixel grid only when it has the same corners (or none). - (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => self.masked_image(im, m, !n.extras().pixelated), + // A color-masked image keeps the colors it hides hidden. + (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => { + let shown = self.doc.shown_image(n, im); + self.masked_image(im, &shown, m, !n.extras().pixelated) + } _ => None, }; if let Some(m) = mask diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index eaff6c781f..d08f1069b4 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -840,6 +840,21 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool) Some(img.pixels().map(|p| ((u32::from(p[0]) * u32::from(p[3]) + back * (255 - u32::from(p[3])) + 127) / 255) as u8).collect()) } +/// The alpha of each pixel of image `blob` (255 for an image without alpha), when it is `width` × +/// `height` pixels. `None` for a CMYK image, another size, or one too large to hold as RGBA or +/// that can't be decoded; as in [`mask_alpha`], the size is read from the header first. +pub(crate) fn image_alpha(blob: &ImageBlob, width: u32, height: u32) -> Option> { + if blob.is_cmyk() { + return None; + } + let reader = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?; + if reader.into_dimensions().ok()? != (width, height) || u64::from(width) * u64::from(height) * 4 > MAX_DECODE { + return None; + } + let img = decoded(&blob.bytes)?.into_rgba8(); + (img.dimensions() == (width, height)).then(|| img.pixels().map(|p| p[3]).collect()) +} + /// Opaque colour `samples` (grey, RGB, or CMYK ink amounts, as `space` says) as a JPEG at /// `quality`, tagged with ICC profile `icc` when given. CMYK JPEGs hold Adobe's inverted samples, /// which the PDF writer's Decode array undoes. diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index b5f6185ea9..9d333eecb3 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -1210,6 +1210,45 @@ fn a_distorted_cmyk_image_and_its_grid_mask_with_the_same_corners_write_it_as_it } } +/// A color-masked CMYK image with a gray mask of its grid keeps its inks and its hidden colors +/// hidden: the image's `/SMask` is the mask's alpha times the alpha of the pixels the color mask +/// shows, so a hidden pixel stays clear where the mask's alpha is not zero, for a distorted image +/// too. +#[test] +fn a_color_masked_cmyk_image_with_a_grid_mask_keeps_its_hidden_colors_hidden() { + for distorted in [false, true] { + let mut d = masked_doc(png(image::GrayImage::from_raw(2, 2, vec![255, 128, 0, 64]).unwrap()), true, false); + // The first pixel hidden, where the mask is fully opaque, and the last half shown. + let alpha = [0, 255, 255, 128]; + let shown = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([0, 90, 200, alpha[(y * 2 + x) as usize]])); + d.images.insert("shown".into(), ImageBlob::new("image/png", png(shown))); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(16.0, 0.0), (24.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y)); + let mut mask = d.node(id).unwrap().extras().mask.clone().unwrap(); + if distorted { + Arc::make_mut(&mut mask.art).set_image_corners(q).unwrap(); + } + let n = d.node_mut(id).unwrap(); + n.extras_mut().mask = Some(mask); + n.extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { + key: "shown".into(), + from: "img".into(), + background: vectorcraft_doc::color_mask::MaskBackground::Colors, + colors: vec![[255, 255, 255]], + contiguous: false, + measure: vectorcraft_doc::color_mask::MaskMatch::Distance, + tolerance: 0.0, + softness: 0.0, + })); + if distorted { + n.set_image_corners(q).unwrap(); + } + let (bytes, smasks) = export_smasks(&d); + assert!(!smasks.is_empty() && smasks.iter().all(|m| m.as_deref() == Some(&[0, 128, 0, 32][..])), "{distorted}: {smasks:?}"); + assert!(distorted || !String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); + } +} + /// A grey mask image with a color mask masks the CMYK image with the pixels it shows: its hidden /// pixels are clear in the image's `/SMask`. #[test] diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index b98407cb7c..354610e4c0 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -97,6 +97,10 @@ pub const MAX_STORAGE_CALLS: usize = 10_000; /// pass it returns [`STORAGE_BUDGET`]. pub const MAX_STORAGE_BYTES: usize = 1 << 30; +/// Bytes a storage call reads or writes for each instruction it costs the run, counted as for +/// [`MAX_STORAGE_BYTES`]: the 1 GiB a run may move costs 16,777,216 instructions. +pub const STORAGE_BYTES_PER_FUEL: u64 = 64; + /// What `vc_call` returns: the command ran, and `vc_call_result` reads its result. pub const CALL_OK: i32 = 0; /// What `vc_call` or `vc_call_result` returns: the id, the arguments or the buffer doesn't lie @@ -163,6 +167,19 @@ impl std::fmt::Display for CallPending { impl wasmi::errors::HostError for CallPending {} +/// What a storage call ends the run with when the instructions it may take can't pay for its bytes +/// ([`STORAGE_BYTES_PER_FUEL`]); the host reports why ([`Run::storage_stop`]). +#[derive(Debug)] +pub(crate) struct StorageStop; + +impl std::fmt::Display for StorageStop { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("storage call") + } +} + +impl wasmi::errors::HostError for StorageStop {} + /// One host import: its name, its type and the permission it needs. pub struct Import { pub name: &'static str, @@ -365,6 +382,18 @@ pub(crate) struct Run { storage: Option>, storage_calls: usize, storage_bytes: usize, + /// The instructions of the call's budget not yet handed to the store, which storage calls also + /// pay from; the host keeps it up to date around each slice. + pub(crate) fuel_left: u64, + /// Bytes storage reads copied into the module's memory beyond the bytes the storage counted for + /// them, such as a settings value answered from memory; they cost instructions at the same rate. + copied_bytes: u64, + /// Instructions the last storage call cost ([`STORAGE_BYTES_PER_FUEL`]), still to be taken. + fuel_owed: u64, + /// Why the call ends after a storage call: the instruction budget when it needed more + /// instructions than it could take, or the deadline or Cancel, checked before a storage call + /// takes from [`Run::fuel_left`] and after every storage call. + pub(crate) storage_stop: Option, /// The commands `vc_call` may run (the manifest's `commandAllowlist`), once the module has /// loaded and when the run has something to run them ([`Run::allow_calls`]); `None` otherwise. allowed: Option>, @@ -395,6 +424,10 @@ impl Run { storage: None, storage_calls: 0, storage_bytes: 0, + fuel_left: 0, + copied_bytes: 0, + fuel_owed: 0, + storage_stop: None, allowed: None, calls: 0, call_bytes: 0, @@ -527,16 +560,48 @@ impl Run { /// Makes one storage call with `call`, on the plug-in's storage and a [`Meter`] holding the /// run's storage bytes left, and counts the call and the bytes it read and wrote → the code for /// a run that has used up its calls or has no storage, else what `call` returns. - fn metered(&mut self, call: impl FnOnce(&dyn Storage, &mut Meter) -> std::result::Result) -> std::result::Result { + /// + /// The run's storage bytes cost one instruction for each whole [`STORAGE_BYTES_PER_FUEL`] + /// bytes, counted over the run, so splitting a transfer into calls costs the same. The meter + /// also holds no more bytes than the `held` instructions in the store pay for, with + /// [`Run::fuel_left`] too while the deadline and Cancel have not come ([`Meter::gated`]), so + /// the call stops before a read or write they can't pay for; one the storage bytes left would + /// allow sets [`Run::storage_stop`]. What the call costs goes to [`Run::fuel_owed`]. + fn metered( + &mut self, + held: u64, + call: impl FnOnce(&dyn Storage, &mut Meter) -> std::result::Result, + ) -> std::result::Result { if self.storage_calls >= MAX_STORAGE_CALLS { return Err(STORAGE_BUDGET); } self.storage_calls += 1; let Some(store) = self.storage.clone() else { return Err(STORAGE_UNAVAILABLE) }; - let mut meter = Meter::new(MAX_STORAGE_BYTES.saturating_sub(self.storage_bytes) as u64); + let before = self.storage_bytes as u64; + let by_bytes = MAX_STORAGE_BYTES.saturating_sub(self.storage_bytes) as u64; + // Bytes up to the end of the last whole unit `fuel` instructions pay for. + let by_fuel = |fuel: u64| { + let units = (before / STORAGE_BYTES_PER_FUEL).saturating_add(fuel).saturating_add(1); + units.saturating_mul(STORAGE_BYTES_PER_FUEL).saturating_sub(before).saturating_sub(1) + }; + // Bytes past what the store's fuel pays for are read or written only before the deadline + // and Cancel, as the host hands out the rest of the budget only then. + let left = by_bytes.min(by_fuel(held.saturating_add(self.fuel_left))); + let mut meter = Meter::gated(left, by_fuel(held), self.deadline.at); let done = call(store.as_ref(), &mut meter); // What the call read before it failed counts too. self.storage_bytes = self.storage_bytes.saturating_add(usize::try_from(meter.used()).unwrap_or(usize::MAX)); + self.fuel_owed = (self.storage_bytes as u64 / STORAGE_BYTES_PER_FUEL).saturating_sub(before / STORAGE_BYTES_PER_FUEL); + // A read or write the run's storage bytes alone allow was refused for its instructions, or + // for the deadline or Cancel. + let refused = meter.refused(); + if matches!(done, Err(StorageError::Budget)) && refused > 0 && refused <= by_bytes.saturating_sub(meter.used()) { + self.storage_stop = Some(match meter.stopped() { + Some(storage::Gate::Cancel) => Error::Cancelled, + Some(storage::Gate::Deadline) => Error::Limit(TIME_BUDGET.into()), + None => Error::Limit("instruction budget".into()), + }); + } done.map_err(|e| storage_code(&e)) } @@ -549,8 +614,8 @@ impl Run { } /// `vc_settings_get` and `vc_cache_read`: copies the value of the key at `name` into the - /// `out_cap` bytes at `out` when it fits → its length. - fn storage_read(&mut self, area: Area, memory: &mut [u8], name: (usize, usize), out: (usize, usize)) -> i32 { + /// `out_cap` bytes at `out` when it fits → its length. The store holds `held` instructions. + fn storage_read(&mut self, area: Area, memory: &mut [u8], name: (usize, usize), out: (usize, usize), held: u64) -> i32 { let key = match Self::storage_name(memory, name.0, name.1) { Ok(key) => key, Err(code) => return code, @@ -559,7 +624,8 @@ impl Run { return STORAGE_OUTSIDE_MEMORY; } // The storage counts what it read whether or not the value fits the buffer. - let got = self.metered(|store, meter| match area { + let counted = self.storage_bytes; + let got = self.metered(held, |store, meter| match area { Area::Settings => store.setting(&key, meter), Area::Cache => store.cache_entry(&key, meter), }); @@ -573,12 +639,18 @@ impl Run { && let Some(dest) = memory.get_mut(out.0..out.0 + value.len()) { dest.copy_from_slice(&value); + // Bytes copied that the storage didn't count, counted over the run like the others. + let uncounted = (value.len() as u64).saturating_sub(self.storage_bytes.saturating_sub(counted) as u64); + let before = self.copied_bytes / STORAGE_BYTES_PER_FUEL; + self.copied_bytes = self.copied_bytes.saturating_add(uncounted); + self.fuel_owed = self.fuel_owed.saturating_add(self.copied_bytes / STORAGE_BYTES_PER_FUEL - before); } len } - /// `vc_settings_set` and `vc_cache_write`: sets the key at `name` to the `value` bytes. - fn storage_write(&mut self, area: Area, memory: &[u8], name: (usize, usize), value: (usize, usize)) -> i32 { + /// `vc_settings_set` and `vc_cache_write`: sets the key at `name` to the `value` bytes. The + /// store holds `held` instructions. + fn storage_write(&mut self, area: Area, memory: &[u8], name: (usize, usize), value: (usize, usize), held: u64) -> i32 { let key = match Self::storage_name(memory, name.0, name.1) { Ok(key) => key, Err(code) => return code, @@ -587,7 +659,7 @@ impl Run { if bytes.len() > area.max_value() { return STORAGE_FULL; } - let written = self.metered(|store, meter| match area { + let written = self.metered(held, |store, meter| match area { Area::Settings => store.set_setting(&key, bytes, meter), Area::Cache => store.set_cache_entry(&key, bytes, meter), }); @@ -595,8 +667,8 @@ impl Run { } /// `vc_settings_delete` and `vc_cache_clear`: removes the key at `name`, or with `vc_cache_clear` - /// and a `name` of no bytes, every cache entry. - fn storage_remove(&mut self, area: Area, memory: &[u8], name: (usize, usize)) -> i32 { + /// and a `name` of no bytes, every cache entry. The store holds `held` instructions. + fn storage_remove(&mut self, area: Area, memory: &[u8], name: (usize, usize), held: u64) -> i32 { let key = match (area, name.1) { (Area::Cache, 0) => None, _ => match Self::storage_name(memory, name.0, name.1) { @@ -604,7 +676,7 @@ impl Run { Err(code) => return code, }, }; - let removed = self.metered(|store, meter| match (area, key) { + let removed = self.metered(held, |store, meter| match (area, key) { (Area::Settings, Some(key)) => store.delete_setting(&key, meter), (Area::Cache, Some(key)) => store.remove_cache_entry(&key), (_, None) => store.clear_cache().map(|_| true), @@ -700,6 +772,35 @@ fn memory_and_host<'a>(caller: &'a mut Caller<'_, Host>) -> Option<(&'a mut [u8] Some(memory.data_and_store_mut(caller)) } +/// Takes what the last storage call cost ([`Run::fuel_owed`]) from the `held` instructions in the +/// store, then from [`Run::fuel_left`]. A call that needed more instructions than those, or that +/// ended after the deadline or Cancel (checked in that order, as after a `vc_call`), ends the run +/// with [`StorageStop`] and the reason in [`Run::storage_stop`]. +fn pay_storage(caller: &mut Caller<'_, Host>, held: u64) -> std::result::Result<(), wasmi::Error> { + let run = &mut caller.data_mut().run; + let owed = std::mem::take(&mut run.fuel_owed); + if run.storage_stop.is_none() { + run.storage_stop = if owed > held.saturating_add(run.fuel_left) { + Some(Error::Limit("instruction budget".into())) + } else if run.deadline.passed() { + Some(Error::Limit(TIME_BUDGET.into())) + } else if vectorcraft_doc::cancel::is_cancelled() { + Some(Error::Cancelled) + } else { + None + }; + } + if run.storage_stop.is_some() { + return Err(wasmi::Error::host(StorageStop)); + } + let from_store = owed.min(held); + run.fuel_left = run.fuel_left.saturating_sub(owed - from_store); + if from_store > 0 { + caller.set_fuel(held - from_store)?; + } + Ok(()) +} + /// An i32 argument as the unsigned offset or length it stands for. fn offset(v: i32) -> usize { v as u32 as usize @@ -726,18 +827,34 @@ pub(crate) fn linker(engine: &Engine, granted: &[Permission]) -> Linker { if !granted.contains(&permission) { continue; } - let _ = linker.func_wrap(MODULE, get, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, out: i32, out_cap: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_read(area, data, (offset(key), offset(key_len)), (offset(out), offset(out_cap))) - }); - let _ = linker.func_wrap(MODULE, set, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, value: i32, value_len: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_write(area, data, (offset(key), offset(key_len)), (offset(value), offset(value_len))) - }); - let _ = linker.func_wrap(MODULE, remove, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_remove(area, data, (offset(key), offset(key_len))) - }); + // A storage call pays for its bytes before it returns ([`pay_storage`]). + let _ = linker.func_wrap( + MODULE, + get, + move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, out: i32, out_cap: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_read(area, data, (offset(key), offset(key_len)), (offset(out), offset(out_cap)), held); + pay_storage(&mut caller, held).map(|()| code) + }, + ); + let _ = linker.func_wrap( + MODULE, + set, + move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, value: i32, value_len: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_write(area, data, (offset(key), offset(key_len)), (offset(value), offset(value_len)), held); + pay_storage(&mut caller, held).map(|()| code) + }, + ); + let _ = + linker.func_wrap(MODULE, remove, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_remove(area, data, (offset(key), offset(key_len)), held); + pay_storage(&mut caller, held).map(|()| code) + }); } if granted.contains(&Permission::Commands) { // A call that can be made pauses the run: the host makes it with what the run was given to diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 1a25e9e6b0..7c4262dd4e 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -191,6 +191,27 @@ fn charge(live: &mut Live, left: &mut u64, cost: u64) -> Result<()> { live.store.set_fuel(held - (cost - from_left)).map_err(wasm_err) } +/// Resumes a run's call with `step`: the store's storage calls may also pay from `left` +/// ([`host::Run::fuel_left`]), and what they took from it comes off `left` when the call pauses → +/// the pause, or the error the call ended with ([`run_err`]). +fn slice(live: &mut Live, left: &mut u64, step: impl FnOnce(&mut Store) -> std::result::Result) -> Result { + live.store.data_mut().run.fuel_left = *left; + let paused = step(&mut live.store); + *left = std::mem::take(&mut live.store.data_mut().run.fuel_left); + paused.map_err(|e| run_err(&mut live.store, e)) +} + +/// Why a storage call ended a run of `store` ([`host::Run::storage_stop`]). +fn stop_reason(store: &mut Store) -> Error { + store.data_mut().run.storage_stop.take().unwrap_or_else(|| Error::Limit("instruction budget".into())) +} + +/// The error `e` that a run of `store` ended with: a storage call's reason ([`host::StorageStop`]) +/// or [`wasm_err`]'s. +fn run_err(store: &mut Store, e: wasmi::Error) -> Error { + if e.downcast_ref::().is_some() { stop_reason(store) } else { wasm_err(e) } +} + fn wasm_err(e: wasmi::Error) -> Error { if e.as_trap_code() == Some(wasmi::TrapCode::OutOfFuel) { Error::Limit("instruction budget".into()) } else { Error::Trap(e.to_string()) } } @@ -306,7 +327,7 @@ impl Plugin { Ok(instance) => instance, Err(e) => { *report = std::mem::take(&mut store.data_mut().run.report); - return Err(wasm_err(e)); + return Err(run_err(&mut store, e)); } }; let memory = @@ -321,7 +342,9 @@ impl Plugin { /// for it. It charges a `memory.fill` or `memory.copy` for its whole length before writing, so /// up to that cost can be left in the store at a pause. Each slice tops the store up to the /// slice size, keeping that fuel, and a run ends with the instruction budget only when the - /// store's fuel and the rest of the budget together can't pay for the next instruction. + /// store's fuel and the rest of the budget together can't pay for the next instruction. A + /// storage call pays for its bytes ([`host::STORAGE_BYTES_PER_FUEL`]) from the store's fuel and + /// the rest of the budget as it is made, and one they can't pay for ends the run. fn call(&self, live: &mut Live, f: &TypedFunc, params: P, fuel: u64, deadline: &Deadline) -> Result { self.call_with(live, f, params, fuel, deadline, None) } @@ -343,11 +366,14 @@ impl Plugin { let give = left.min(FUEL_SLICE); left -= give; live.store.set_fuel(give).map_err(wasm_err)?; - let mut call = f.call_resumable(&mut live.store, params).map_err(wasm_err)?; + let mut call = slice(live, &mut left, |store| f.call_resumable(store, params))?; loop { match call { TypedResumableCall::Finished(r) => return Ok(r), TypedResumableCall::HostTrap(inv) => { + if inv.host_error().downcast_ref::().is_some() { + return Err(stop_reason(&mut live.store)); + } let pending = live.store.data_mut().run.pending.take(); let (Some((id, args, size)), Some(bridge)) = (pending, bridge.as_deref_mut()) else { return Err(Error::Trap("unexpected host trap".into())); @@ -361,7 +387,7 @@ impl Plugin { charge(live, &mut left, returned as u64 / 64)?; deadline.check()?; vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; - call = inv.resume(&mut live.store, &[Val::I32(code)]).map_err(wasm_err)?; + call = slice(live, &mut left, |store| inv.resume(store, &[Val::I32(code)]))?; } TypedResumableCall::OutOfFuel(inv) => { let need = inv.required_fuel(); @@ -375,7 +401,7 @@ impl Plugin { let fill = total.min(FUEL_SLICE.max(need)).max(held); left -= fill - held; live.store.set_fuel(fill).map_err(wasm_err)?; - call = inv.resume(&mut live.store).map_err(wasm_err)?; + call = slice(live, &mut left, |store| inv.resume(store))?; } } } diff --git a/crates/plugins/src/storage.rs b/crates/plugins/src/storage.rs index b7de23c45a..fb32e94513 100644 --- a/crates/plugins/src/storage.rs +++ b/crates/plugins/src/storage.rs @@ -49,12 +49,33 @@ pub enum StorageError { pub struct Meter { left: u64, used: u64, + refused: u64, + /// Past `free` bytes in all, a read or write happens only before the deadline `until` and + /// Cancel ([`vectorcraft_doc::cancel`]); `stopped` records which refused one. + free: u64, + until: Option, + stopped: Option, +} + +/// What made a gated [`Meter`] refuse a read or write. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Gate { + /// The run was canceled. + Cancel, + /// The run's deadline passed. + Deadline, } impl Meter { /// A meter that lets a call read and write `left` bytes. pub fn new(left: u64) -> Self { - Meter { left, used: 0 } + Meter { left, used: 0, refused: 0, free: u64::MAX, until: None, stopped: None } + } + + /// A meter that lets a call read and write `left` bytes, those past the first `free` only + /// before `until` and Cancel. + pub(crate) fn gated(left: u64, free: u64, until: web_time::Instant) -> Self { + Meter { free, until: Some(until), ..Meter::new(left) } } /// A meter with no limit, for callers that don't count. @@ -63,20 +84,46 @@ impl Meter { } /// Counts `bytes` about to be read or written → [`StorageError::Budget`], counting nothing, - /// when that is more than is left. + /// when that is more than is left, or when they pass the free bytes of a gated meter after its + /// deadline or Cancel. pub fn take(&mut self, bytes: u64) -> Result<(), StorageError> { if bytes > self.left { + self.refused = bytes; return Err(StorageError::Budget); } + if self.used.saturating_add(bytes) > self.free { + // The deadline first, as the host checks it between two slices. + let closed = if self.until.is_some_and(|at| web_time::Instant::now() >= at) { + Some(Gate::Deadline) + } else { + vectorcraft_doc::cancel::is_cancelled().then_some(Gate::Cancel) + }; + if closed.is_some() { + self.stopped = closed; + self.refused = bytes; + return Err(StorageError::Budget); + } + } self.left -= bytes; self.used = self.used.saturating_add(bytes); Ok(()) } + /// What made the meter refuse a read or write past its free bytes ([`Meter::gated`]), if + /// anything did. + pub(crate) fn stopped(&self) -> Option { + self.stopped + } + /// The bytes counted so far. pub fn used(&self) -> u64 { self.used } + + /// The bytes of the last read or write the meter refused (0 when it refused none). + pub(crate) fn refused(&self) -> u64 { + self.refused + } } impl std::fmt::Display for StorageError { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index ae99846c69..f4cb2e103b 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -621,9 +621,9 @@ fn charged( key: &str, meter: &mut Meter, ) -> Result>, StorageError> { - let value = kept.lock().unwrap().get(key).cloned(); - meter.take(value.as_ref().map_or(0, |v| v.len() as u64))?; - Ok(value) + let kept = kept.lock().unwrap(); + meter.take(kept.get(key).map_or(0, |v| v.len() as u64))?; + Ok(kept.get(key).cloned()) } impl Storage for Kept { @@ -777,6 +777,224 @@ fn a_read_into_too_small_a_buffer_still_counts_its_bytes() { registry::set_storage(id, None); } +/// Storage calls cost the run one instruction for every 64 bytes they read or write: reading a +/// 64 MiB cache entry, or writing 1 MiB to the cache 64 times, ends a run of 1 M instructions with +/// its instruction budget and finishes within 2 M. A call the run can't pay for reads and writes +/// nothing, a call pays from the budget not yet in the store, a call past the 1 GiB still returns +/// `STORAGE_BUDGET`, and a small read finishes on a small budget. +#[test] +fn storage_calls_pay_instructions_for_the_bytes_they_move() { + use vectorcraft_plugins::host::{MAX_STORAGE_BYTES, STORAGE_BUDGET, STORAGE_DONE}; + use vectorcraft_plugins::storage::MAX_CACHE_ENTRY; + let id = "test.storage.fuel"; + let kept = std::sync::Arc::new(Kept::default()); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + kept.settings.lock().unwrap().insert("zoom".into(), b"hello".to_vec()); + registry::set_storage(id, Some(kept.clone())); + let run = |first: &str, fuel_base: u64| { + let limits = Limits { fuel_base, fuel_per_byte: 0, ..Limits::default() }; + Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), first, INPUT)), limits).unwrap().run(INPUT.as_bytes(), b"{}") + }; + let zoom = "(i32.const 0x2000) (i32.const 4)"; + let reading = expect(&format!("(call $vc_cache_read {zoom} (i32.const 0x3000) (i32.const 0))"), MAX_CACHE_ENTRY as i32); + // 17 more pages of memory, then 1 MiB of them written to the cache 64 times. + let write = expect(&format!("(call $vc_cache_write {zoom} (i32.const 0x20000) (i32.const 1048576))"), STORAGE_DONE); + let writing = format!( + "(local $n i32) (drop (memory.grow (i32.const 17))) (local.set $n (i32.const 64)) \ + (loop $work {write} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ); + let budget = Err(Error::Limit("instruction budget".into())); + let done = Ok(INPUT.as_bytes().to_vec()); + let small = expect(&format!("(call $vc_settings_get {zoom} (i32.const 0x3000) (i32.const 16))"), 5); + assert_eq!(run(&small, 10_000), done, "a small read on 10,000 instructions"); + // Growing the memory by 17 pages costs about 17,400 instructions and writing 1 MiB 16,384: a + // write the run can't pay for writes nothing. + let once = format!("(drop (memory.grow (i32.const 17))) {write}"); + assert_eq!(run(&once, 30_000), budget, "1 MiB written on 30,000 instructions"); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged"); + assert_eq!(run(&once, 60_000), done, "1 MiB written on 60,000 instructions"); + assert_eq!(kept.cache_bytes(), 1 << 20, "the entry is written"); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + assert_eq!(run(&reading, 1_000_000), budget, "a 64 MiB read on 1 M instructions"); + assert_eq!(run(&reading, 2_000_000), done, "a 64 MiB read on 2 M instructions"); + assert_eq!(run(&writing, 1_000_000), budget, "64 MiB written on 1 M instructions"); + assert_eq!(run(&writing, 2_000_000), done, "64 MiB written on 2 M instructions"); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + // About 19.7 M instructions of fills leave less of the first 20 M slice than a 64 MiB read + // costs; the read pays from the rest of the budget. + let burning = format!( + "(local $n i32) (drop (memory.grow (i32.const 130))) (local.set $n (i32.const 149)) \ + (loop $burn (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $burn (local.get $n))) {reading}" + ); + assert_eq!(run(&burning, 21_000_000), done, "a read across two slices within the budget"); + assert_eq!(run(&burning, 20_500_000), budget, "a read across two slices over the budget"); + // What the read took from the rest of the budget is gone: six more 8 MiB fills (about 786,000 + // instructions) don't fit the 21 M. + let more = format!( + "{burning} (local.set $n (i32.const 6)) (loop $more (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $more (local.get $n)))" + ); + assert_eq!(run(&more, 21_000_000), budget, "fills after the read over the budget"); + // With 8 MiB of the run's 1 GiB of storage bytes left and instructions for less, a 64 MiB read + // returns `STORAGE_BUDGET`, since the bytes alone refuse it, and the run goes on. + let rest = MAX_STORAGE_BYTES - 15 * MAX_CACHE_ENTRY - (8 << 20); + kept.cache.lock().unwrap().insert("x".into(), vec![0; rest]); + let x = expect("(call $vc_cache_read (i32.const 0x200d) (i32.const 1) (i32.const 0x3000) (i32.const 0))", rest as i32); + let over = expect(&format!("(call $vc_cache_read {zoom} (i32.const 0x3000) (i32.const 0))"), STORAGE_BUDGET); + let near = [vec![reading.clone(); 15], vec![x, over]].concat().concat(); + assert_eq!(run(&near, 16_700_000), done, "a read past the 1 GiB"); + // Bytes are counted over the run: 9,000 writes of 63 bytes, each under 64, cost about 8,860 + // instructions more than 9,000 writes of none, not 0 or 9,000 as rounding each write down or up + // would. Each run's fewest instructions are found by bisection. + let looped = |len: u32| { + let write = expect(&format!("(call $vc_cache_write {zoom} (i32.const 0x2000) (i32.const {len}))"), STORAGE_DONE); + format!( + "(local $n i32) (local.set $n (i32.const 9000)) \ + (loop $work {write} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ) + }; + let fewest = |first: &str| { + let (mut lo, mut hi) = (10_000, 50_000_000); + assert_eq!(run(first, hi), done, "the writes finish"); + while lo + 1 < hi { + let mid = (lo + hi) / 2; + match run(first, mid) { + Ok(_) => hi = mid, + Err(Error::Limit(why)) if why == "instruction budget" => lo = mid, + Err(e) => panic!("the writes failed on {mid} instructions: {e:?}"), + } + } + hi + }; + let (none, small) = (fewest(&looped(0)), fewest(&looped(63))); + assert!((none + 8_800..=none + 8_900).contains(&small), "63-byte writes take {small} instructions, empty ones {none}"); + registry::set_storage(id, None); +} + +/// A storage call that needs more of the budget than the store holds takes it only before Cancel +/// and the deadline: after either, a 32 MiB write near the end of the first 20 M slice writes +/// nothing and the run ends as canceled or with its time budget. +#[test] +fn after_cancel_or_the_deadline_a_storage_call_takes_no_more_of_the_budget() { + use vectorcraft_plugins::host::STORAGE_DONE; + use vectorcraft_plugins::storage::MAX_CACHE_ENTRY; + let id = "test.storage.cancel"; + let kept = std::sync::Arc::new(Kept::default()); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + registry::set_storage(id, Some(kept.clone())); + // Growing by 512 pages and 148 fills of 8 MiB take about 19.9 M instructions; the write costs + // 524,288. + let write = expect("(call $vc_cache_write (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 33554432))", STORAGE_DONE); + let first = format!( + "(local $n i32) (drop (memory.grow (i32.const 512))) (local.set $n (i32.const 148)) \ + (loop $burn (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $burn (local.get $n))) {write}" + ); + let limits = Limits { fuel_base: 21_000_000, fuel_per_byte: 0, ..Limits::default() }; + let p = Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), limits.clone()).unwrap(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")); + assert_eq!(r, Err(Error::Cancelled)); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged"); + let timed = Limits { wall_time_ms: 0, ..limits }; + assert_eq!(p.run_limited(INPUT.as_bytes(), b"{}", &timed), Err(Error::Limit("time budget".into()))); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged after the deadline"); + // With both, the time budget, as between two slices. + let r = vectorcraft_doc::cancel::scope(&token, None, || p.run_limited(INPUT.as_bytes(), b"{}", &timed)); + assert_eq!(r, Err(Error::Limit("time budget".into()))); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Ok(INPUT.as_bytes().to_vec()), "the same run without Cancel"); + assert_eq!(kept.cache_bytes(), 32 << 20, "the entry is written"); + registry::set_storage(id, None); +} + +/// The host checks the deadline and Cancel after every storage call, also one the store's +/// instructions pay for: after either, a 1 MiB cache write is the run's last storage call, and the +/// write after it doesn't happen. +#[test] +fn a_run_past_its_deadline_or_canceled_stops_after_a_storage_call() { + use vectorcraft_plugins::host::STORAGE_DONE; + let id = "test.storage.after"; + let kept = std::sync::Arc::new(Kept::default()); + registry::set_storage(id, Some(kept.clone())); + let first = format!( + "(drop (memory.grow (i32.const 17))) {} {}", + expect("(call $vc_cache_write (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 1048576))", STORAGE_DONE), + expect("(call $vc_cache_write (i32.const 0x200d) (i32.const 1) (i32.const 0x20000) (i32.const 1048576))", STORAGE_DONE), + ); + let p = Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), Limits::default()).unwrap(); + let written = || { + let cache = kept.cache.lock().unwrap(); + let names = (cache.contains_key("zoom"), cache.contains_key("x")); + drop(cache); + kept.cache.lock().unwrap().clear(); + names + }; + let timed = Limits { wall_time_ms: 0, ..p.limits().clone() }; + assert_eq!(p.run_limited(INPUT.as_bytes(), b"{}", &timed), Err(Error::Limit("time budget".into()))); + assert_eq!(written(), (true, false), "after the deadline"); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + assert_eq!(vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")), Err(Error::Cancelled)); + assert_eq!(written(), (true, false), "after Cancel"); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Ok(INPUT.as_bytes().to_vec()), "the same run before both"); + assert_eq!(written(), (true, true), "before both"); + registry::set_storage(id, None); +} + +/// A store that answers every setting with the same value without counting its bytes, as the app's +/// store answers a get from the settings it keeps in memory. +struct Remembered(Vec); + +impl Storage for Remembered { + fn setting(&self, _: &str, _: &mut Meter) -> Result>, StorageError> { + Ok(Some(self.0.clone())) + } + fn set_setting(&self, _: &str, _: &[u8], _: &mut Meter) -> Result<(), StorageError> { + Ok(()) + } + fn delete_setting(&self, _: &str, _: &mut Meter) -> Result { + Ok(false) + } + fn cache_entry(&self, _: &str, _: &mut Meter) -> Result>, StorageError> { + Ok(None) + } + fn set_cache_entry(&self, _: &str, _: &[u8], _: &mut Meter) -> Result<(), StorageError> { + Ok(()) + } + fn remove_cache_entry(&self, _: &str) -> Result { + Ok(false) + } + fn clear_cache(&self) -> Result { + Ok(0) + } + fn cache_bytes(&self) -> u64 { + 0 + } +} + +/// A settings get the store answers without counting bytes still costs the bytes it copies into +/// the module's memory: 2,000 gets of a 64 KiB value (128,000 KiB copied) end a run of 1 M +/// instructions with its instruction budget and finish within 4 M. +#[test] +fn settings_gets_answered_from_memory_pay_for_the_bytes_they_copy() { + let id = "test.storage.copied"; + registry::set_storage(id, Some(std::sync::Arc::new(Remembered(vec![7; 65536])))); + let get = expect("(call $vc_settings_get (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 65536))", 65536); + let first = format!( + "(local $n i32) (drop (memory.grow (i32.const 2))) (local.set $n (i32.const 2000)) \ + (loop $work {get} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ); + let run = |fuel_base: u64| { + let limits = Limits { fuel_base, fuel_per_byte: 0, ..Limits::default() }; + Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), limits).unwrap().run(INPUT.as_bytes(), b"{}") + }; + assert_eq!(run(1_000_000), Err(Error::Limit("instruction budget".into())), "on 1 M instructions"); + assert_eq!(run(4_000_000), Ok(INPUT.as_bytes().to_vec()), "on 4 M instructions"); + registry::set_storage(id, None); +} + /// A plug-in reaches only the storage of its own id, and a plug-in with none (not installed with a /// plug-in store, as on the web) gets `STORAGE_UNAVAILABLE`. #[test] diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index fff66aa142..cad3127abd 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -205,30 +205,28 @@ pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pal /// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures /// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a -/// pixel that becomes transparent, and for every pixel when `palette` is empty. -pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { - let px = rgba.as_chunks::<4>().0; - let colors = opaque_colors(px, o, false); +/// pixel that becomes transparent, and for every pixel when `palette` is empty. `f` gets each +/// pixel's entry in pixel order, worked out one pixel at a time. +pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]], mut f: impl FnMut(Option)) { let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); let index = PaletteIndex::new(&pal, o.reduction.weights()); - colors - .iter() - .zip(px) - .map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) }) - .collect() + for p in rgba.as_chunks::<4>().0 { + f(if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(opaque_color(p, o, false).map(f32::from))) }); + } } /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> { + px.iter().map(|p| opaque_color(p, o, gray)).collect() +} + +/// The color of the pixel `p` when opaque, as [`opaque_colors`] gives it. +fn opaque_color(p: &[u8; 4], o: &PaletteOptions, gray: bool) -> [u8; 3] { let matte = o.matte.unwrap_or([255; 3]); let blend = o.matte.is_some() || !o.transparency; - px.iter() - .map(|p| { - let a = if blend { p[3] as u32 } else { 255 }; - let c = [0, 1, 2].map(|i| ((p[i] as u32 * a + matte[i] as u32 * (255 - a) + 127) / 255) as u8); - if gray { [luma(c); 3] } else { c } - }) - .collect() + let a = if blend { p[3] as u32 } else { 255 }; + let c = [0, 1, 2].map(|i| ((p[i] as u32 * a + matte[i] as u32 * (255 - a) + 127) / 255) as u8); + if gray { [luma(c); 3] } else { c } } /// Map the pixels `px` (their opaque `colors`) to `palette` with `dither`, then drop the entries diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index 7eb480a414..79e36b3f5f 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -93,6 +93,13 @@ fn lossy_makes_runs_and_smaller_gifs() { let mut kept = ix.clone(); lossy(&mut kept, &px, 100, &fixed); assert_eq!(kept, ix); + // With one fixed entry of three, no pixel moves into or out of it, and the others still merge. + let palette: Vec<[u8; 3]> = vec![[100, 0, 0], [110, 0, 0], [120, 0, 0]]; + let indices: Vec = vec![1, 0, 0, 1, 1, 2]; + let px: Vec = indices.iter().flat_map(|&i| palette[usize::from(i)].into_iter().chain([255])).collect(); + let mut part = Indexed { width: 2, height: 3, palette, transparent: None, indices }; + lossy(&mut part, &px, 100, &[0]); + assert_eq!(part.indices, vec![1, 0, 0, 1, 1, 1]); } #[test] diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index b7c70345d0..5d01cc8438 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -46,21 +46,25 @@ pub(crate) struct IncludeRef { } /// What variables hold, as a check learns it: the member chains assigned to them, and the ones -/// holding a File or Folder object. +/// holding a File or Folder object, with the ones of those that every assignment the check read gave +/// a Folder object ([`Analyzer::folders`]). #[derive(Clone, Debug, Default)] pub(crate) struct Known { pub bound: HashMap, pub files: HashSet, + pub folders: HashSet, } impl Known { - /// The names known. + /// The names known, a name that may hold a File object counting twice: a Folder that becomes a + /// possible File object ([`Known::add`]) changes it too. pub fn len(&self) -> usize { - self.bound.len() + self.files.len() + self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) } /// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already - /// bound keeps its chain. + /// bound keeps its chain. A name that holds a File or Folder object on both sides holds a Folder + /// object only when both sides say so; otherwise it may hold a File object. pub fn add(&mut self, other: Known, entries: usize) { for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { @@ -68,7 +72,14 @@ impl Known { } } for name in other.files { - if self.files.len() < entries { + if self.files.contains(&name) { + if !other.folders.contains(&name) { + self.folders.remove(&name); + } + } else if self.files.len() < entries { + if other.folders.contains(&name) { + self.folders.insert(name.clone()); + } self.files.insert(name); } } @@ -255,10 +266,11 @@ struct Assign { after_new: bool, } -/// What a value the check follows holds: a member chain, or a File or Folder object. +/// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it +/// is a Folder object whatever the path names: [`Operand::file_step`]). enum Held { Chain(String), - File, + File { folder: bool }, } /// `name = (`: a value in grouping parentheses. Its value is the last operand in each pair (ECMA-262 @@ -302,8 +314,9 @@ enum Operand { FileMember { folder: bool }, /// `File.openDialog`, `File.saveDialog` or `Folder.selectDialog` came first: its `(` is next. FileDialog, - /// A call of `File`, `Folder` or one of their dialogs came first, and its `)` is still to come. - FileCall, + /// A call of `File`, `Folder` or one of their dialogs came first, and its `)` is still to come + /// (`folder` for `new Folder(…)`). + FileCall { folder: bool }, /// Grouping parentheses came first, and their `)` is still to come ([`Paren`] only). Pair, /// A member chain came first and is still being read. @@ -320,15 +333,23 @@ impl Operand { /// `Folder.selectDialog(…)`, `Folder.` ([`catalog::FOLDER_PLACES`]) or a variable holding /// one. `file`: `t` is the platform's `File` or `Folder`; `alias`: `t` names a variable holding a /// File or Folder object. + /// + /// Only `new Folder(…)`, `new Folder` and `Folder.` are Folder objects whatever the path + /// names. `Folder(…)` gives a File object when the path names a file, `Folder.selectDialog(…)` + /// gives a File or Folder object for what the user picks, `Folder.current` is the one place a + /// script can assign, and a variable another variable was assigned to may hold a File object. fn file_step(self, t: &Sig, file: bool, alias: bool) -> Operand { match self { Operand::Start if t.word("new") => Operand::New, Operand::Start if file => Operand::FileName { new: false, folder: t.text == catalog::FOLDER }, Operand::New if file => Operand::FileName { new: true, folder: t.text == catalog::FOLDER }, - Operand::Start if alias => Operand::Done(Held::File), - Operand::FileName { .. } | Operand::FileDialog if t.is("(") => Operand::FileCall, + Operand::Start if alias => Operand::Done(Held::File { folder: false }), + Operand::FileName { new, folder } if t.is("(") => Operand::FileCall { folder: new && folder }, + Operand::FileDialog if t.is("(") => Operand::FileCall { folder: false }, Operand::FileName { new: false, folder } if t.is(".") => Operand::FileMember { folder }, - Operand::FileMember { folder: true } if catalog::FOLDER_PLACES.contains(&t.text) => Operand::Done(Held::File), + Operand::FileMember { folder: true } if catalog::FOLDER_PLACES.contains(&t.text) => { + Operand::Done(Held::File { folder: t.text != catalog::FOLDER_CURRENT }) + } Operand::FileMember { folder } if (if folder { catalog::FOLDER_DIALOGS } else { catalog::FILE_DIALOGS }).contains(&t.text) => { Operand::FileDialog } @@ -337,9 +358,13 @@ impl Operand { } /// The operand is a File or Folder object when the `)` of its parentheses comes next: a complete - /// one, or `new File` or `new Folder` without arguments. - fn holds_file(&self) -> bool { - matches!(self, Operand::Done(Held::File) | Operand::FileName { new: true, .. }) + /// one, or `new File` or `new Folder` without arguments. `Some(true)` for a Folder object whatever + /// the path names. + fn held_file(&self) -> Option { + match self { + Operand::Done(Held::File { folder }) | Operand::FileName { new: true, folder } => Some(*folder), + _ => None, + } } } @@ -458,6 +483,14 @@ struct Saved { chain: Option, /// It held a File or Folder object. file: bool, + /// It held a Folder object. + folder: bool, + /// It was in [`Analyzer::maybe_files`]. + maybe_file: bool, + /// The function body or `catch` block declares it, so whether an assignment in it gave the name + /// a value that may be a File object is put back too. For an outer name an assignment emptied, + /// that stays. + local: bool, /// For a root of the document model: whether the script's own variable hid the root. shadowed: Option, /// It was a platform name the script had a meaning of its own for. @@ -525,6 +558,14 @@ struct Analyzer<'s, 'a, 'l> { bound: HashMap, /// Variables holding a File or Folder object. files: HashSet, + /// The variables in `files` holding a Folder object whatever the path names ([`Held::File`]). + folders: HashSet, + /// The variables that an assignment in this scan or in what the scan started with gave a value + /// that may be a File object. Assignments in a branch or a function body are read in order, so + /// such a variable never counts as holding a Folder object ([`Analyzer::folder`]). + maybe_files: HashSet, + /// `maybe_files` ran out of room: no variable counts as holding a Folder object. + maybe_files_full: bool, /// The platform names ([`platform_name`]) the script declares or assigns a meaning of its own /// for: they no longer stand for the platform's objects. own_names: HashSet, @@ -551,8 +592,8 @@ struct Analyzer<'s, 'a, 'l> { /// block it names. catch_names: HashMap, /// The calls of `File`, `Folder` and their dialogs still open, by the bracket depth outside their - /// `(`, up to [`crate::Limits::nesting`] of them. - file_calls: Vec, + /// `(`, up to [`crate::Limits::nesting`] of them, each true for a call that gives a Folder object. + file_calls: Vec<(usize, bool)>, /// The values in grouping parentheses, the values without them that may hold a File, and the /// values of compound assignments, being read, the innermost last, up to /// [`crate::Limits::nesting`] of them. @@ -593,6 +634,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { shadowed: [false; 4], bound: known.bound.clone(), files: known.files.clone(), + folders: known.folders.clone(), + maybe_files: known.files.difference(&known.folders).cloned().collect(), + maybe_files_full: false, own_names: HashSet::new(), scopes: vec![], declared, @@ -685,9 +729,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let consumed = self.continue_chain(&t); let before = self.depth(); if t.kind == T::Punct { - t.file = self.bracket(&t); + let held = self.bracket(&t); + t.file = held.is_some(); + t.folder = held == Some(true); } else { t.file = self.folder_place(&t); + t.folder = t.file && t.text != catalog::FOLDER_CURRENT; } self.conditional(&t); self.add_parameter(&t); @@ -793,19 +840,37 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn bind(&mut self, name: String, path: String) { self.files.remove(&name); + self.folders.remove(&name); if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) { self.bound.insert(name, path); } } - /// `name` holds a File or Folder object. - fn hold_file(&mut self, name: String) { + /// `name` holds a File or Folder object (`folder` for a Folder object whatever the path names). + fn hold_file(&mut self, name: String, folder: bool) { self.bound.remove(&name); + self.folders.remove(&name); + if !folder && !self.maybe_files.contains(&name) { + if self.acc.room(self.maybe_files.len()) { + self.maybe_files.insert(name.clone()); + } else { + self.maybe_files_full = true; + } + } if self.files.contains(&name) || self.acc.room(self.files.len()) { + if folder { + self.folders.insert(name.clone()); + } self.files.insert(name); } } + /// `name` holds a Folder object whatever the path names, and no assignment the check read gave it + /// a value that may be a File object. + fn folder(&self, name: &str) -> bool { + !self.maybe_files_full && self.files.contains(name) && self.folders.contains(name) && !self.maybe_files.contains(name) + } + /// `t`, when it names a parameter of the function whose body's `{` is still to come: kept, up to /// [`crate::Limits::entries`] of them, for the body to declare. A `catch` block's parameter is /// kept for the block. @@ -848,6 +913,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// `name` is declared in the innermost function body (`var name`, `function name`, a + /// parameter): what it held outside is kept ([`Analyzer::keep_outer`]) as the body's own, and + /// the body's variable starts with no assignment read. + fn keep_own(&mut self, name: &str) { + self.keep_outer(name); + if let Some(saved) = self.scopes.last_mut().and_then(|s| s.saved.get_mut(name)) { + saved.local = true; + self.maybe_files.remove(name); + } + } + /// The names [`Declared`] has for the function body whose `{` starts at `start`. fn declared_in(&mut self, start: usize) -> &'a [&'s str] { let declared = self.declared; @@ -865,7 +941,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// outside is kept to put back when the body closes. A name the body's table has no room for /// stays as it is. fn hoist(&mut self, name: &str) { - self.keep_outer(name); + self.keep_own(name); if self.scopes.last().is_some_and(|s| s.saved.contains_key(name)) { self.empty(name); } @@ -889,7 +965,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// What `name` holds now. fn saved(&self, name: &str) -> Saved { let shadowed = catalog::DOM_ROOTS.iter().position(|r| *r == name).and_then(|i| self.shadowed.get(i).copied()); - Saved { chain: self.bound.get(name).cloned(), file: self.files.contains(name), shadowed, own: self.own_names.contains(name) } + Saved { + chain: self.bound.get(name).cloned(), + file: self.files.contains(name), + folder: self.folders.contains(name), + maybe_file: self.maybe_files.contains(name), + local: false, + shadowed, + own: self.own_names.contains(name), + } } /// `name` holds `saved` again. @@ -908,6 +992,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { self.files.remove(&name); } + if saved.folder { + self.folders.insert(name.clone()); + } else { + self.folders.remove(&name); + } + if saved.local && saved.maybe_file { + self.maybe_files.insert(name.clone()); + } else if saved.local { + self.maybe_files.remove(&name); + } if saved.own { self.own_names.insert(name.clone()); } else { @@ -961,6 +1055,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.make_own(name); self.bound.remove(name); self.files.remove(name); + self.folders.remove(name); self.hide_root(name); } @@ -975,9 +1070,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // ---------- brackets ---------- - /// An open or close bracket: true for the `)` that ends a call of `File` or `Folder`, or grouping - /// parentheses that hold a File or Folder object ([`Analyzer::close_parens`]). - fn bracket(&mut self, t: &Sig<'s>) -> bool { + /// An open or close bracket: `Some` for the `)` that ends a call of `File` or `Folder`, or grouping + /// parentheses that hold a File or Folder object ([`Analyzer::close_parens`]), `Some(true)` when + /// the object is a Folder object. + fn bracket(&mut self, t: &Sig<'s>) -> Option { match t.text { "(" | "[" | "{" => { if std::mem::take(&mut self.suspend) @@ -997,17 +1093,20 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The first `{` after `catch` and its parentheses at this depth opens its block. let depth = self.depth(); let catch = if t.text == "{" { self.catch.take().filter(|(d, _)| *d == depth).and_then(|(_, name)| name) } else { None }; - let file_call = t.text == "(" && self.calls_for_file(); - if file_call && self.file_calls.len() < self.acc.limits.nesting { - self.file_calls.push(self.depth()); + let file_call = if t.text == "(" { self.calls_for_file() } else { None }; + if let Some(folder) = file_call + && self.file_calls.len() < self.acc.limits.nesting + { + self.file_calls.push((self.depth(), folder)); } self.open(t); if let Some(name) = catch && self.catches.len() < self.acc.limits.nesting { - let saved = self.saved(&name); + let saved = Saved { local: true, ..self.saved(&name) }; let outer = self.catch_names.insert(name.clone(), self.depth()); self.empty(&name); + self.maybe_files.remove(&name); self.catches.push(Catch { depth: self.depth(), name, saved, outer }); } if params { @@ -1021,7 +1120,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The parameters are the body's own names, and so are the names it declares. for name in params { self.acc.steps = self.acc.steps.saturating_add(1); - self.keep_outer(&name); + self.keep_own(&name); self.unbind(&name); } for &name in self.declared_in(t.start) { @@ -1042,16 +1141,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } self.close_scopes(); let grouped = self.close_parens(t); - if t.text == ")" && self.file_calls.last() == Some(&self.depth()) { - self.file_calls.pop(); - return true; + let depth = self.depth(); + if t.text == ")" + && let Some((_, folder)) = self.file_calls.pop_if(|(d, _)| *d == depth) + { + return Some(folder); } return grouped; } } _ => {} } - false + None } fn open(&mut self, t: &Sig<'s>) { @@ -1071,18 +1172,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// A `(` here calls something that gives a File or Folder object: `File` or `Folder` (with or /// without `new`), or `File.openDialog`, `File.saveDialog` or `Folder.selectDialog`, each the - /// platform's. - fn calls_for_file(&self) -> bool { + /// platform's. `Some(true)` when it gives a Folder object whatever the path names: only + /// `new Folder(…)` ([`Operand::file_step`]). + fn calls_for_file(&self) -> Option { let [h0, h1, h2, h3] = self.h; let platform = |s: Option, name: &str| word(s, name) && !self.own_names.contains(name); - let constructor = (platform(h0, catalog::FILE) || platform(h0, catalog::FOLDER)) && !member_mark(h1); - let dialog = h0.filter(|s| s.kind == T::Ident).is_some_and(|m| { - is(h1, ".") - && !member_mark(h3) - && ((platform(h2, catalog::FILE) && catalog::FILE_DIALOGS.contains(&m.text)) - || (platform(h2, catalog::FOLDER) && catalog::FOLDER_DIALOGS.contains(&m.text))) - }); - constructor || dialog + if (platform(h0, catalog::FILE) || platform(h0, catalog::FOLDER)) && !member_mark(h1) { + return Some(word(h0, catalog::FOLDER) && word(h1, "new")); + } + let m = h0.filter(|s| s.kind == T::Ident && is(h1, ".") && !member_mark(h3))?; + ((platform(h2, catalog::FILE) && catalog::FILE_DIALOGS.contains(&m.text)) + || (platform(h2, catalog::FOLDER) && catalog::FOLDER_DIALOGS.contains(&m.text))) + .then_some(false) } /// `t` names one of the platform's `Folder` places after `Folder.` (`Folder.temp`): a Folder @@ -1113,7 +1214,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if self.in_catch(name.text) { self.declare_in_catch(name.text); } else if self.scopes.last().is_some_and(|s| !s.saved.contains_key(name.text)) { - self.keep_outer(name.text); + self.keep_own(name.text); self.unbind(name.text); } } @@ -1140,7 +1241,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } }; let Some(c) = self.catches.get_mut(i) else { return }; - let empty = Saved { chain: None, file: false, shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), own: platform_name(name) }; + let empty = Saved { + chain: None, + file: false, + folder: false, + maybe_file: false, + local: false, + shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), + own: platform_name(name), + }; let outside = std::mem::replace(&mut c.saved, empty); if let Some(scope) = self.scopes.last_mut() { scope.saved.insert(name.to_string(), outside); @@ -1159,8 +1268,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.assign = Some(a); } else if (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text) { self.start_value(a.name, Operand::FileName { new: a.after_new, folder: t.text == catalog::FOLDER }); - } else if !a.after_new && t.kind == T::Ident && self.files.contains(t.text) { - self.start_value(a.name, Operand::Done(Held::File)); + } else if !a.after_new && self.alias(t) { + self.start_value(a.name, Operand::Done(Held::File { folder: false })); } else if !a.after_new && t.is("(") { self.start_group(a.name); } else { @@ -1257,14 +1366,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn group_step(&mut self, t: &Sig<'s>, started: bool, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = t.kind == T::Ident && self.files.contains(t.text); + let alias = self.alias(t); let Some(g) = self.groups.last_mut().filter(|g| !g.closed) else { return }; if after < g.level { // The `)` of the innermost pair: the operand, when complete, is the pair's value and the // operand of the pair around it. let held = match std::mem::replace(&mut g.operand, Operand::Other) { Operand::Done(held) => Some(held), - Operand::FileName { new: true, .. } => Some(Held::File), + Operand::FileName { new: true, folder } => Some(Held::File { folder }), _ => None, }; g.operand = held.map_or(Operand::Other, Operand::Done); @@ -1275,8 +1384,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if before > g.level { // Inside a bracket of the operand: the `)` back at the pair's depth ends a call of `File`, // `Folder` or one of their dialogs. - if after == g.level && matches!(g.operand, Operand::FileCall) { - g.operand = Operand::Done(Held::File); + if after == g.level + && let Operand::FileCall { folder } = g.operand + { + g.operand = Operand::Done(Held::File { folder }); } return; } @@ -1313,7 +1424,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn paren_step(&mut self, t: &Sig<'s>, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = t.kind == T::Ident && self.files.contains(t.text); + let alias = self.alias(t); if let Some(p) = self.parens.last_mut() { if before == p.level { p.operand = match std::mem::replace(&mut p.operand, Operand::Other) { @@ -1325,7 +1436,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The `)` of a call of `File`, `Folder` or a dialog, or of grouping parentheses, ends a // File or Folder object when [`Analyzer::bracket`] set its [`Sig::file`]. p.operand = match p.operand { - Operand::FileCall | Operand::Pair if t.file => Operand::Done(Held::File), + Operand::FileCall { .. } | Operand::Pair if t.file => Operand::Done(Held::File { folder: t.folder }), _ => Operand::Other, }; } @@ -1335,11 +1446,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// The grouping parentheses that the bracket `t` closed, if any (a bracket closes one level): true - /// when `t` is their `)` and their operand is a File or Folder object. - fn close_parens(&mut self, t: &Sig<'s>) -> bool { + /// The grouping parentheses that the bracket `t` closed, if any (a bracket closes one level): `Some` + /// when `t` is their `)` and their operand is a File or Folder object, `Some(true)` for a Folder + /// object. + fn close_parens(&mut self, t: &Sig<'s>) -> Option { let depth = self.depth(); - self.parens.pop_if(|p| depth < p.level).is_some_and(|p| t.is(")") && p.operand.holds_file()) + self.parens.pop_if(|p| depth < p.level).filter(|_| t.is(")")).and_then(|p| p.operand.held_file()) + } + + /// `t` names a variable holding a File or Folder object. + fn alias(&self, t: &Sig<'s>) -> bool { + t.kind == T::Ident && self.files.contains(t.text) } /// `t` follows the last `)` of a grouped value, or ends a value without parentheses at the depth @@ -1365,7 +1482,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let complete = (g.closed || g.bare) && ends; match g.operand { Operand::Done(Held::Chain(path)) if complete => self.bind(g.name, path), - Operand::Done(Held::File) | Operand::FileName { new: true, .. } if complete => self.hold_file(g.name), + Operand::Done(Held::File { folder }) | Operand::FileName { new: true, folder } if complete => self.hold_file(g.name, folder), _ => self.unbind(&g.name), } } @@ -1449,7 +1566,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let bracket: &str = bracket.encode_utf8(&mut buf); self.acc.problem(report::UNCLOSED_BRACKET, Some(line), self.file, Some(bracket)); } - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files) }; + // A variable that any assignment gave a value that may be a File object leaves as one. + let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); + let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..19806fb9ad 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -136,12 +136,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// `name`, a property of `receiver` read with `.` or as a string literal in brackets, `before` - /// coming before the receiver: when it is a File object's setter, the next token says whether it - /// is set ([`Pending::Setter`]). An update operator in `before` is a prefix (`++f.length`) when - /// the receiver is on its line, or when it starts a line or comes where an expression may start; - /// otherwise it ends the operand before it (`i++` and a line break, then `f.length`). + /// coming before the receiver: when it is the setter of an object that may be a File object (not + /// of one that is a Folder object whatever the path names), the next token says whether it is set + /// ([`Pending::Setter`]). An update operator in `before` is a prefix + /// (`++f.length`) when the receiver is on its line, or when it starts a line or comes where an + /// expression may start; otherwise it ends the operand before it (`i++` and a line break, then + /// `f.length`). fn setter(&mut self, name: &str, receiver: Option>, before: Option>, line: Option) { - if catalog::FILE_SETTERS.contains(&name) && self.file_receiver(receiver, before) { + if catalog::FILE_SETTERS.contains(&name) && self.held_file(receiver, before) == Some(false) { // Before a receiver that ends in `)` (`new File(i++).length`), the operator is inside the // parentheses. let update = before.filter(|b| (b.is("++") || b.is("--")) && receiver.is_some_and(|r| r.kind == T::Ident)); @@ -328,7 +330,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// (not a property of the same name), or a File or Folder object made in place or held in /// grouping parentheses ([`Sig::file`]). fn file_receiver(&self, receiver: Option>, before: Option>) -> bool { - receiver.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(before) && self.files.contains(r.text))) + self.held_file(receiver, before).is_some() + } + + /// What [`Self::file_receiver`] finds: `Some(true)` for a Folder object whatever the path names + /// ([`Sig::folder`], [`Analyzer::folder`]), `Some(false)` for an object that may be a File object, + /// and `None` for anything else. + fn held_file(&self, receiver: Option>, before: Option>) -> Option { + let r = receiver?; + if r.file { + Some(r.folder) + } else if r.kind == T::Ident && !member_mark(before) && self.alias(&r) { + Some(self.folder(r.text)) + } else { + None + } } fn string(&mut self, t: &Sig<'s>, line: Option) { diff --git a/crates/scriptcheck/src/analyze/sig.rs b/crates/scriptcheck/src/analyze/sig.rs index 1cde2df0fe..edcb642cc5 100644 --- a/crates/scriptcheck/src/analyze/sig.rs +++ b/crates/scriptcheck/src/analyze/sig.rs @@ -14,6 +14,9 @@ pub(super) struct Sig<'s> { /// name in `Folder.temp` and the other places of [`catalog::FOLDER_PLACES`], or the `)` of /// grouping parentheses that hold only such an object or a variable holding one (`(f)`). pub(super) file: bool, + /// The object that [`Sig::file`] marks the end of is a Folder object whatever the path names: + /// `new Folder(…)`, a place of [`catalog::FOLDER_PLACES`], or grouping parentheses that hold one. + pub(super) folder: bool, /// A statement may start at the token ([`crate::lex::Token::stmt`]). pub(super) stmt: bool, /// An expression may start at the token ([`crate::lex::Token::expr`]). @@ -25,7 +28,7 @@ pub(super) struct Sig<'s> { impl<'s> Sig<'s> { /// The significant token `t`, after a line break when `nl` is set. pub(super) fn of(t: &Token<'s>, nl: bool) -> Self { - Sig { kind: t.kind, text: t.text, line: t.line, nl, file: false, stmt: t.stmt, expr: t.expr, start: t.start } + Sig { kind: t.kind, text: t.text, line: t.line, nl, file: false, folder: false, stmt: t.stmt, expr: t.expr, start: t.start } } pub(super) fn is(&self, punct: &str) -> bool { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..0045c764f2 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -40,6 +40,8 @@ pub(crate) const FOLDER_DIALOGS: &[&str] = &["selectDialog"]; pub(crate) const INSTANCE_DIALOGS: &[&str] = &["openDlg", "saveDlg", "selectDlg"]; pub(crate) const FOLDER_PLACES: &[&str] = &["appData", "appPackage", "commonFiles", "current", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; +/// The `Folder` place a script can assign. +pub(crate) const FOLDER_CURRENT: &str = "current"; pub(crate) const EXECUTE: &str = "execute"; pub(crate) const OPEN: &str = "open"; /// The open modes that write: write, append and edit. diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..b771cc6417 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -564,6 +564,95 @@ fn setting_a_files_length_or_flags_writes_it() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4, 5, 6, 7, 8, 10, 12][..])); } +/// `new Folder(…)` and the `Folder` places always give a Folder object, which has no `length`, +/// `hidden` or `readonly` setter. `Folder(…)` gives a File object when the path names a file, +/// `Folder.selectDialog()` gives a File or Folder object, and a variable assigned another variable +/// may hold either, so setting those writes. Removing a folder still writes. +#[test] +fn setting_a_folders_length_or_flags_does_not_write() { + let r = report(concat!( + "var d = new Folder(p);\n", + "d.length = 0;\n", + "d.hidden = true;\n", + "Folder.temp.length = 0;\n", + "(new Folder(q)).length = 0;\n", + "(Folder.desktop)['readonly'] = true;\n", + "Folder(p).readonly = true;\n", + "var e = Folder.selectDialog();\n", + "e.length = 0;\n", + "var g = (d);\n", + "g['length'] = 0;\n", + "var h = Folder(p);\n", + "h.hidden = true;\n", + "(Folder(p)).length = 0;\n", + "d.remove();\n", + "Folder.current.hidden = true;\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[7, 9, 11, 13, 14, 15, 16][..])]); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[7, 9, 11, 13, 14, 15, 16][..])); +} + +/// A File object assigned to a function's own variable, its parameter or a `catch` block's +/// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter +/// starts without what the outer variable of the same name was assigned. +#[test] +fn a_file_in_a_local_variable_leaves_an_outer_folder_alone() { + let r = report(concat!( + "var d = new Folder(p);\n", + "function f(e) { var d = new File(q); e = new File(q); d.length = 0; }\n", + "var e = new Folder(p);\n", + "try { x(); } catch (d) { d = new File(q); }\n", + "d.length = 0; e.hidden = true;\n", + "var g = new Folder(p);\n", + "function h() { g = y(); g = new File(q); }\n", + "g.length = 0;\n", + "var k = new File(q);\n", + "function m(n) { var k = new Folder(p); k.length = 0; n = new Folder(p); n.hidden = true; }\n", + "try { x(); } catch (k) { k = new Folder(p); k.readonly = true; }\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[2, 8][..])]); +} + +/// The check reads branches and function bodies in order, so a variable that any assignment gives an +/// object that may be a File object keeps counting as one, in the same file, in a function the code +/// after it assigns, and across included files. +#[test] +fn a_variable_that_may_hold_a_file_counts_as_one() { + let r = report(concat!( + "var d;\n", + "if (c) { d = new File(p); } else { d = new Folder(p); }\n", + "d.length = 0;\n", + "function w() { h.hidden = true; }\n", + "var h = new Folder(q);\n", + "if (c) h = File(p);\n", + "var k = new Folder(q);\n", + "k.length = 0;\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[3, 4][..])]); + for lib in ["d = new File(q);\n", "d = Folder.selectDialog();\n", "var x = new File(q); d = x;\n"] { + let mut m = mem(&[("lib.jsxinc", lib)]); + let r = check("main.jsx", b"#include 'lib.jsxinc'\nvar d = new Folder(p);\nd.length = 0;\n", Some(&mut m), &Limits::default()); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[3][..])], "{lib}"); + } + // The function that may give `d` a File object only does so once `e` holds one, which the + // second scan learns. + let r = report(concat!( + "var d = new Folder(p);\n", + "function write() { d.length = 0; }\n", + "function assign() { d = e; }\n", + "var e = new File(q);\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[2][..])]); + let mut m = mem(&[("lib.jsxinc", "d = Folder.temp;\n")]); + let r = check("main.jsx", b"#include 'lib.jsxinc'\nvar d = new Folder(p);\nd.length = 0;\n", Some(&mut m), &Limits::default()); + assert!(r.outside.is_empty(), "{:?}", r.outside); +} + #[test] fn a_function_after_a_line_that_ends_a_statement_is_a_declaration() { let r = report("var n = 1\nfunction File() {}\nFile('x');\nvar m = 2 /* a\n */ function Socket() {}\nnew Socket();\n"); diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index c1a59d7022..310b9c8e6f 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-svg = { workspace = true } +craft-xml = { workspace = true } craft-mime = { workspace = true } # Which paths stored in documents may be opened. craft-docpath = { workspace = true } diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index b92e888b57..481db1f8a2 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1,4 +1,4 @@ -use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_valid}; +use super::output::{sanitize_id, valid_xml_value, xml_attr_escape}; use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ @@ -888,7 +888,7 @@ impl Writer<'_> { if !valid_xml_value(url) { self.warn("Link URLs containing invalid XML characters had those characters removed"); } - self.line(&format!("", xml_attr_valid(url))); + self.line(&format!("", xml_attr_escape(url))); self.depth += 1; self.node_body(n); self.depth -= 1; diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index 3ed101340a..00fb760c03 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -1,8 +1,9 @@ use super::*; -/// XML 1.0 literal attribute whitespace is normalized to spaces; references retain the value. +/// Escape a double-quoted attribute, retaining VectorCraft's apostrophe entity spelling. pub(super) fn xml_attr_escape(s: &str) -> String { - xml_escape(s).replace('\t', " ").replace('\n', " ").replace('\r', " ") + let escaped = craft_xml::esc_attr(s); + if escaped.contains('\'') { escaped.replace('\'', "'") } else { escaped } } /// Escape type for XML content. Characters XML 1.0 does not allow are dropped, except the line @@ -12,21 +13,15 @@ pub(super) fn xml_text(s: &str) -> String { .chars() .filter_map(|c| match c { '\u{b}' | '\u{c}' => Some(' '), - c if valid_xml_value(c.encode_utf8(&mut [0; 4])) => Some(c), + c if craft_xml::is_xml_char(c) => Some(c), _ => None, }) .collect(); xml_escape(&s) } -/// `s` without the characters XML 1.0 does not allow, ready for a double-quoted attribute. -pub(super) fn xml_attr_valid(s: &str) -> String { - let s: String = s.chars().filter(|c| valid_xml_value(c.encode_utf8(&mut [0; 4]))).collect(); - xml_attr_escape(&s) -} - pub(super) fn valid_xml_value(s: &str) -> bool { - s.chars().all(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}')) + s.chars().all(craft_xml::is_xml_char) } /// An XML name without a colon (an NCName): a letter or `_`, then [`xml_name_char`]s. diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index f8bc712117..289fcb81ba 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -1,4 +1,4 @@ -use super::output::{xml_attr_escape, xml_attr_valid, xml_text}; +use super::output::{xml_attr_escape, xml_text}; use super::{ Affine, AppearanceItem, Arc, BTreeSet, BezPath, BlendMode, CharStyle, FillRule, FontDb, FontFace, GradientKind, HashMap, Justify, Node, NodeId, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, Styling, TextKind, TextObject, Writer, base64_encode, css, css_string, fmt_num, @@ -199,7 +199,7 @@ impl Writer<'_> { Some(named) if !id.is_empty() && !id.contains(" data-name=\"") => format!(" data-name=\"{}\"", xml_attr_escape(named)), _ => String::new(), }; - format!("{name} role=\"img\" aria-label=\"{}\"", xml_attr_valid(&text)) + format!("{name} role=\"img\" aria-label=\"{}\"", xml_attr_escape(&text)) } else { String::new() }; diff --git a/crates/svg/tests/it/data_attributes.rs b/crates/svg/tests/it/data_attributes.rs index 60edf3dd60..1d411143f0 100644 --- a/crates/svg/tests/it/data_attributes.rs +++ b/crates/svg/tests/it/data_attributes.rs @@ -32,10 +32,10 @@ fn native_data(raw: &str) -> Document { } #[test] fn imported_decimal_whitespace_references_survive_export() { - let doc = import(&svg(r#""#)).unwrap(); + let doc = import(&svg(r#""#)).unwrap(); assert_eq!( named(&doc, "shape").extras().attrs.as_deref().unwrap().data, - [("value".into(), "a\nb".into()), ("tab".into(), "a\tb".into()), ("cr".into(), "a\rb".into())] + [("value".into(), "a\nb".into()), ("tab".into(), "a\tb".into()), ("cr".into(), "a\rb".into()), ("mixed".into(), "a\t\"'<>&\r\n雲".into()),] ); for styling in styles() { for minify in [false, true] { @@ -45,6 +45,8 @@ fn imported_decimal_whitespace_references_survive_export() { for (key, value) in [("data-value", "a\nb"), ("data-tab", "a\tb"), ("data-cr", "a\rb")] { assert_eq!(n.attribute(key), Some(value)); } + assert_eq!(n.attribute("data-mixed"), Some("a\t\"'<>&\r\n雲")); + assert!(text.contains(r#"data-mixed="a "'<>& 雲""#)); let back = import(&text).unwrap(); assert_eq!(named(&back, "shape").extras().attrs.as_deref().unwrap().data, named(&doc, "shape").extras().attrs.as_deref().unwrap().data); } diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 046db94dfd..1b8d9cd04d 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -374,8 +374,6 @@ impl FontDb { #[cfg(not(target_arch = "wasm32"))] fn scan_font_dirs(&self) -> usize { - // Files may have been installed since: other versions are looked for again. - self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear(); let mut catalog = Catalog::new(); let mut aliases: HashMap> = HashMap::new(); let mut postscript = PostScriptNames::new(); @@ -455,6 +453,9 @@ impl FontDb { let _change = self.cataloged.get().is_some().then(crate::test_fonts::font_change); *self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = Some(ScanStamp { paths, modified: modified_at }); *self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog; + // Files may have been installed since: other versions are looked for again, in this + // catalog. A version lookup made during the scan read the previous one. + self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear(); *self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases; *self.postscript.write().unwrap_or_else(|e| e.into_inner()) = postscript; // Faces loaded from a file this scan did not catalog (the font was removed, or its folder diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 0a991c669f..aed9d29679 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -360,13 +360,25 @@ impl RetypeIndex { /// [`Self::all_matches`], and when the shape fits no glyph as it is, its contours read the /// other way round: for a part of a compound path, which Make Compound Path may have turned so - /// it cuts a hole in the paths behind it. + /// it cuts a hole in the paths behind it. When neither reading fits, the contours are read the + /// way their depth gives, outer contours one way and their counters the other, both ways round: + /// an even-odd compound paints the same whichever way each contour runs, so an o's counter may + /// run the same way as its outer contour. pub fn matches_either_way(&self, shape: &BezPath) -> Vec { let found = self.matches_read(shape, shape); if !found.is_empty() { return found; } - self.matches_read(shape, &shape.reverse_subpaths()) + let found = self.matches_read(shape, &shape.reverse_subpaths()); + if !found.is_empty() { + return found; + } + let Some(nested) = nested_reading(shape) else { return vec![] }; + let found = self.matches_read(shape, &nested); + if !found.is_empty() { + return found; + } + self.matches_read(shape, &nested.reverse_subpaths()) } /// [`Self::all_matches`] of `shape`, its contours read as in `reading` (the same outline). @@ -880,39 +892,7 @@ pub fn clusters(path: &BezPath) -> Vec { }, } } - let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); - // Up to MAX_CONTAINMENT_PROBES of each contour's anchor points, evenly spread: a contour lies in - // another only when every one of them does. - let probes: Vec> = subs - .iter() - .map(|s| { - let anchors: Vec = s.elements().iter().filter_map(|e| e.end_point()).collect(); - let step = anchors.len().div_ceil(MAX_CONTAINMENT_PROBES).max(1); - anchors.into_iter().step_by(step).collect() - }) - .collect(); - // Each contour's container: the smallest contour around it. - let parent: Vec> = (0..subs.len()) - .map(|i| { - let (Some(bi), Some(pi)) = (boxes.get(i), probes.get(i)) else { return None }; - if pi.is_empty() { - return None; - } - (0..subs.len()) - .filter(|&j| j != i) - .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) - .filter(|(_, bj, sj)| { - bj.area() > bi.area() - && bj.x0 <= bi.x0 - && bj.y0 <= bi.y0 - && bj.x1 >= bi.x1 - && bj.y1 >= bi.y1 - && pi.iter().all(|p| sj.winding(*p) != 0) - }) - .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) - .map(|(j, _, _)| j) - }) - .collect(); + let parent = containers(&subs); let root = |mut i: usize| { // Containers are strictly larger, so the chain ends; the bound keeps it so. for _ in 0..subs.len() { @@ -935,6 +915,90 @@ pub fn clusters(path: &BezPath) -> Vec { groups.into_iter().map(|(_, p)| p).collect() } +/// Each contour's container among `subs` (one contour each): the smallest other contour that holds +/// it, `None` for an outer contour. +fn containers(subs: &[BezPath]) -> Vec> { + let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); + // Up to MAX_CONTAINMENT_PROBES of each contour's anchor points, evenly spread: a contour lies in + // another only when every one of them does. + let probes: Vec> = subs + .iter() + .map(|s| { + let anchors: Vec = s.elements().iter().filter_map(|e| e.end_point()).collect(); + let step = anchors.len().div_ceil(MAX_CONTAINMENT_PROBES).max(1); + anchors.into_iter().step_by(step).collect() + }) + .collect(); + // Each contour's container: the smallest contour around it. + (0..subs.len()) + .map(|i| { + let (Some(bi), Some(pi)) = (boxes.get(i), probes.get(i)) else { return None }; + if pi.is_empty() { + return None; + } + (0..subs.len()) + .filter(|&j| j != i) + .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) + .filter(|(_, bj, sj)| { + bj.area() > bi.area() + && bj.x0 <= bi.x0 + && bj.y0 <= bi.y0 + && bj.x1 >= bi.x1 + && bj.y1 >= bi.y1 + && pi.iter().all(|p| sj.winding(*p) != 0) + }) + .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) + .map(|(j, _, _)| j) + }) + .collect() +} + +/// `path` with each contour turned to run the way its depth gives (an outer contour one way, its +/// counters the other, what lies in those the first way again), the outer contours keeping the way +/// the first of them runs. `None` when that turns no contour (the path read as it is), for a +/// contour that encloses no area, and for more than [`MAX_CONTOURS`] contours. +fn nested_reading(path: &BezPath) -> Option { + let mut subs: Vec = vec![]; + for el in path.elements() { + if matches!(el, PathEl::MoveTo(_)) { + if subs.len() >= MAX_CONTOURS { + return None; + } + subs.push(BezPath::new()); + } + subs.last_mut()?.push(*el); + } + let parent = containers(&subs); + let depth = |mut i: usize| { + let mut d = 0usize; + // Containers are strictly larger, so the chain ends; the bound keeps it so. + for _ in 0..subs.len() { + match parent.get(i).copied().flatten() { + Some(p) => { + i = p; + d += 1; + } + None => break, + } + } + d + }; + let areas: Vec = subs.iter().map(Shape::area).collect(); + if areas.iter().any(|a| !a.is_normal()) { + return None; + } + let outer = (0..subs.len()).find(|&i| depth(i) == 0).and_then(|i| areas.get(i)).map(|a| a.signum())?; + let turned: Vec = areas.iter().enumerate().map(|(i, a)| a.signum() != if depth(i) % 2 == 0 { outer } else { -outer }).collect(); + if turned.iter().all(|t| !*t) { + return None; + } + let mut out = BezPath::new(); + for (s, t) in subs.iter().zip(&turned) { + out.extend(if *t { s.reverse_subpaths() } else { s.clone() }.iter()); + } + Some(out) +} + /// `a` wrapped into −π..π. fn wrapped(a: f64) -> f64 { (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI @@ -2271,6 +2335,81 @@ mod tests { assert!(clusters(&BezPath::new()).is_empty()); } + #[test] + fn the_nested_reading_turns_counters_against_their_outer_contour() { + let split = |p: &BezPath| -> Vec { + let mut out: Vec = vec![]; + for el in p.elements() { + if matches!(el, PathEl::MoveTo(_)) { + out.push(BezPath::new()); + } + out.last_mut().unwrap().push(*el); + } + out + }; + let join = |cs: &[BezPath]| { + let mut p = BezPath::new(); + for c in cs { + p.extend(c.iter()); + } + p + }; + let cs = split(&letter()); + let (outer, counter) = (cs[0].clone(), cs[1].clone()); + let (same, opposite) = if outer.area().signum() == counter.area().signum() { + (counter.clone(), counter.reverse_subpaths()) + } else { + (counter.reverse_subpaths(), counter.clone()) + }; + // A counter running the same way as its outer contour is turned; the outer one is kept. + let read = nested_reading(&join(&[outer.clone(), same.clone()])).unwrap(); + let rs = split(&read); + assert_eq!(rs[0], outer); + assert_eq!(rs[1].area().signum(), opposite.area().signum()); + // So is the outer contour's way when it comes second. + let read = nested_reading(&join(&[opposite.clone(), outer.reverse_subpaths()])).unwrap(); + let rs = split(&read); + assert_eq!(rs[1], outer.reverse_subpaths()); + assert_eq!(rs[0].area().signum(), outer.area().signum()); + // Already nested so: nothing to turn. + assert!(nested_reading(&join(&[outer.clone(), opposite])).is_none()); + // A contour enclosing no area gives none. + let mut flat = BezPath::new(); + flat.move_to((0.0, 0.0)); + flat.line_to((10.0, 0.0)); + flat.close_path(); + assert!(nested_reading(&join(&[outer, flat])).is_none()); + } + + #[test] + fn a_part_with_some_contours_turned_still_matches_exactly() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(crate::test_fonts::named_copy(false, ("Turntest", "Regular", "Version 1.000", "Turntest-Regular")).unwrap()), 1); + let face = db.face("Turntest", "Regular").unwrap(); + let o = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o')); + let mut cs: Vec = vec![]; + for el in o.elements() { + if matches!(el, PathEl::MoveTo(_)) { + cs.push(BezPath::new()); + } + cs.last_mut().unwrap().push(*el); + } + assert_eq!(cs.len(), 2, "an o is two contours"); + let keys = std::iter::once(shape_key(&o).unwrap()).collect(); + let index = RetypeIndex::build(&db, vec![face], &keys); + assert!(!index.all_matches(&o).is_empty()); + for turned in 0..2 { + let mut shape = BezPath::new(); + for (i, c) in cs.iter().enumerate() { + shape.extend(if i == turned { c.reverse_subpaths() } else { c.clone() }.iter()); + } + assert!(index.all_matches(&shape).is_empty(), "contour {turned} turned is no glyph as it is"); + assert!(index.all_matches(&shape.reverse_subpaths()).is_empty(), "nor read the other way round"); + let found = index.matches_either_way(&shape); + assert!(found.iter().any(|m| m.ch == 'o'), "contour {turned} turned still matches the o"); + } + } + #[test] fn the_same_corners_joined_another_way_are_another_outline() { let poly = |pts: &[(f64, f64)]| { diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d8f91f8d50..3666fb156e 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -105,12 +105,17 @@ impl Drop for SteadyFonts { /// [`SteadyFonts`] for `db`. Catalogs `db`'s installed fonts first: a first scan does not wait for /// any guard, so this thread can wait for one running on another thread while it holds a guard. A -/// thread's first guard waits for the font changes under way or waiting. +/// thread's first guard waits for a font change under way, and for a waiting change that can start +/// now. It does not wait for a change that is waiting for guards other threads hold: the thread +/// waiting for this guard may hold one of them. pub fn steady_fonts(db: &crate::FontDb) -> SteadyFonts { db.ensure_catalog(); if STEADY.with(std::cell::Cell::get) == 0 { let mut s = steadiness(); - while !CHANGING.with(std::cell::Cell::get) && (s.changing || s.waiting > 0) { + let waits = |s: &Steadiness| !CHANGING.with(std::cell::Cell::get) && (s.changing || (s.waiting > 0 && s.holders == s.holders_waiting)); + #[cfg(test)] + gate_decisions().push((std::thread::current().id(), GateAsk::Guard, waits(&s))); + while waits(&s) { s = await_steadiness(s); } s.holders += 1; @@ -150,7 +155,10 @@ pub(crate) fn font_change() -> FontChange { font_changers().push(std::thread::current().id()); s.waiting += 1; s.holders_waiting += usize::from(holder); - while s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 } { + let waits = |s: &Steadiness| s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 }; + #[cfg(test)] + gate_decisions().push((std::thread::current().id(), GateAsk::Change, waits(&s))); + while waits(&s) { s = await_steadiness(s); } s.waiting -= 1; @@ -175,6 +183,22 @@ pub(crate) fn font_changers() -> std::sync::MutexGuard<'static, Vec std::sync::MutexGuard<'static, Vec<(std::thread::ThreadId, GateAsk, bool)>> { + static DECISIONS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + DECISIONS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The family of [`variable_font`]. pub const VARIABLE_FAMILY: &str = "Varitest Sans"; @@ -1991,6 +2015,101 @@ pub fn pair_kerning_font() -> Option> { Some(builder.build()) } +/// The family of [`positive_kerning_font`]. +pub const POSITIVE_KERNING_FAMILY: &str = "Poskern Sans"; + +/// The units [`positive_kerning_font`] adds to the advance of an i that another i follows. +pub const POSITIVE_KERNING_UNITS: i16 = 120; + +/// The bundled Source Sans 3 Regular as family [`POSITIVE_KERNING_FAMILY`], its `GPOS` replaced by +/// one `kern` pair, i followed by i, that adds [`POSITIVE_KERNING_UNITS`] to the first glyph's +/// advance. `None` when it can't be built. +pub fn positive_kerning_font() -> Option> { + use write_fonts::tables::gpos::{Gpos, PairPos, PairSet, PairValueRecord, PositionLookup, PositionLookupList, ValueRecord}; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let i = GlyphId16::new(u16::try_from(font.charmap().map('i')?.to_u32()).ok()?); + let record = PairValueRecord::new(i, ValueRecord::new().with_x_advance(POSITIVE_KERNING_UNITS), ValueRecord::new()); + let coverage = CoverageFormat1::new(vec![i]); + let pos = PairPos::format_1(coverage.into(), vec![PairSet::new(vec![record])]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0])), vec![]))]); + let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"kern"), Feature::new(None, vec![0]))]); + let lookups = PositionLookupList::new(vec![PositionLookup::Pair(Lookup::new(Default::default(), vec![pos]))]); + let family = POSITIVE_KERNING_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Poskern Sans Regular"), (6, "PoskernSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&Gpos::new(scripts, features, lookups)).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`space_kerning_font`]. +pub const SPACE_KERNING_FAMILY: &str = "Spacekern Sans"; + +/// The units [`space_kerning_font`] adds to the advance of an i that a space follows. +pub const SPACE_KERNING_UNITS: i16 = 130; + +/// The bundled Source Sans 3 Regular as family [`SPACE_KERNING_FAMILY`], its `GPOS` replaced by one +/// `kern` pair, i followed by a space, that adds [`SPACE_KERNING_UNITS`] to the first glyph's +/// advance. `None` when it can't be built. +pub fn space_kerning_font() -> Option> { + space_kerned_font(SPACE_KERNING_FAMILY, "Spacekern", SPACE_KERNING_UNITS) +} + +/// The family of [`space_narrowing_font`]. +pub const SPACE_NARROWING_FAMILY: &str = "Spacenarrow Sans"; + +/// The units [`space_narrowing_font`] takes off the advance of an i that a space follows. +pub const SPACE_NARROWING_UNITS: i16 = 130; + +/// [`space_kerning_font`] as family [`SPACE_NARROWING_FAMILY`], its pair taking +/// [`SPACE_NARROWING_UNITS`] off the first glyph's advance instead. `None` when it can't be built. +pub fn space_narrowing_font() -> Option> { + space_kerned_font(SPACE_NARROWING_FAMILY, "Spacenarrow", -SPACE_NARROWING_UNITS) +} + +/// The bundled Source Sans 3 Regular as `family` (`short` Sans in its PostScript name), its `GPOS` +/// replaced by one `kern` pair, i followed by a space, that adds `units` to the first glyph's +/// advance. +fn space_kerned_font(family: &str, short: &str, units: i16) -> Option> { + use write_fonts::tables::gpos::{Gpos, PairPos, PairSet, PairValueRecord, PositionLookup, PositionLookupList, ValueRecord}; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let (i, space) = (gid('i')?, gid(' ')?); + let record = PairValueRecord::new(space, ValueRecord::new().with_x_advance(units), ValueRecord::new()); + let coverage = CoverageFormat1::new(vec![i]); + let pos = PairPos::format_1(coverage.into(), vec![PairSet::new(vec![record])]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0])), vec![]))]); + let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"kern"), Feature::new(None, vec![0]))]); + let lookups = PositionLookupList::new(vec![PositionLookup::Pair(Lookup::new(Default::default(), vec![pos]))]); + let (full, ps) = (format!("{family} Regular"), format!("{short}Sans-Regular")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &ps)])?; + let mut builder = FontBuilder::new(); + builder.add_table(&Gpos::new(scripts, features, lookups)).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`twin_font`]: two versions of one family and style. pub const TWIN_FAMILY: &str = "Twintest Sans"; diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 08f6584186..b6a1e8c1aa 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -4,6 +4,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use crate::fontdb::fonts_outside; +use crate::test_fonts::GateAsk; use crate::*; const FAMILY: &str = "Sysfont Sans3"; @@ -83,10 +84,8 @@ fn steady_fonts_hold_back_other_threads_font_changes() { let _steady = guarded.then(|| crate::test_fonts::steady_fonts(&db)); db.add_font(font) }); - let id = adding.thread().id(); - while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { - std::thread::yield_now(); - } + let waits = first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()); + assert_eq!(waits, Some(true), "guarded {guarded}: the other thread's change waits for the guard"); assert_eq!(db.generation(), before, "guarded {guarded}: the other thread's change waits for the guard"); let listed = db.families().iter().any(|f| f == crate::test_fonts::VARIABLE_FAMILY); assert!(!listed, "guarded {guarded}: the other thread publishes the font only once the guard is dropped"); @@ -99,10 +98,8 @@ fn steady_fonts_hold_back_other_threads_font_changes() { let steady = crate::test_fonts::steady_fonts(&db); std::thread::scope(|scope| { let adding = scope.spawn(|| db.add_font(crate::test_fonts::two_axis_font().unwrap())); - let id = adding.thread().id(); - while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { - std::thread::yield_now(); - } + let waits = first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()); + assert_eq!(waits, Some(true), "the other thread's change waits for the guard"); let before = db.generation(); assert!(db.add_font(crate::test_fonts::variable_font().unwrap()) > 0); let after = db.generation(); @@ -114,6 +111,65 @@ fn steady_fonts_hold_back_other_threads_font_changes() { }); } +/// Whether the first `ask` that the thread `id` made of the font gate waited, once the thread has +/// made it; `None` when `finished` says the thread ended without making it. +fn first_decision(id: std::thread::ThreadId, ask: GateAsk, finished: impl Fn() -> bool) -> Option { + loop { + let done = finished(); + let waits = crate::test_fonts::gate_decisions().iter().find(|(t, a, _)| *t == id && *a == ask).map(|(_, _, waits)| *waits); + if waits.is_some() || done { + return waits; + } + std::thread::yield_now(); + } +} + +/// While a thread holds [`test_fonts::steady_fonts`] and a font change on another thread waits for +/// it, a third thread's first guard does not wait for that change, which cannot start before the +/// first guard is dropped. +#[test] +fn a_first_guard_does_not_wait_for_a_change_that_waits_for_other_guards() { + let db = FontDb::with_font_dirs(vec![]); + std::thread::scope(|scope| { + let steady = crate::test_fonts::steady_fonts(&db); + let adding = scope.spawn(|| db.add_font(crate::test_fonts::variable_font().unwrap())); + assert_eq!(first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()), Some(true), "the change waits for the guard"); + let guarding = scope.spawn(|| drop(crate::test_fonts::steady_fonts(&db))); + let waits = first_decision(guarding.thread().id(), GateAsk::Guard, || guarding.is_finished()); + assert_eq!(waits, Some(false), "the new guard does not wait for the change that waits for this thread's guard"); + guarding.join().unwrap(); + drop(steady); + assert!(adding.join().unwrap() > 0, "the font is new to this database"); + }); +} + +/// A version of a family looked up while a rescan of the font folders is under way, before the +/// rescan publishes what it found, does not hide a version of that family the rescan found. +#[test] +fn a_version_looked_up_during_a_rescan_is_found_after_it() { + use crate::test_fonts::{TWIN_FAMILY, TWIN_VERSIONS, twin_font}; + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-rescan-versions", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Older.ttf"), twin_font(false).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + assert_eq!(db.load_system_fonts(), 1); + let face = db.face(TWIN_FAMILY, "Regular").expect("the installed face"); + assert_eq!(face.version, TWIN_VERSIONS[0]); + std::fs::write(dir.join("Newer.ttf"), twin_font(true).unwrap()).unwrap(); + let versions = |db: &FontDb| db.versions(&face).iter().map(|f| f.version.clone()).collect::>(); + std::thread::scope(|scope| { + let steady = crate::test_fonts::steady_fonts(&db); + let rescanning = scope.spawn(|| db.load_system_fonts()); + let waits = first_decision(rescanning.thread().id(), GateAsk::Change, || rescanning.is_finished()); + assert_eq!(waits, Some(true), "the rescan waits for the guard before it publishes"); + assert_eq!(versions(&db), [TWIN_VERSIONS[0]], "before the rescan publishes, only the older file is cataloged"); + drop(steady); + assert_eq!(rescanning.join().unwrap(), 2); + }); + assert_eq!(versions(&db), TWIN_VERSIONS, "the version the rescan found is loaded"); + std::fs::remove_dir_all(dir).unwrap(); +} + /// The first scan of a database's installed fonts does not wait for [`test_fonts::steady_fonts`] /// held for another database, so a thread holding one can catalog a database that another thread /// is scanning. diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 71f039724f..27b63477da 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -575,3 +575,6 @@ mod tests_inflate_shading; #[cfg(test)] mod tests_limits; + +#[cfg(test)] +mod tests_curves; diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d883ad14b8..c945d12d1a 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -41,6 +41,11 @@ impl Camera { let f = perspective_scale(self.eye, v.2); Point::new(self.origin.x + v.0 * f, self.origin.y + v.1 * f) } + /// The view-space point at depth `z` that [`Camera::project`] takes to `p`. + pub(super) fn unproject(&self, p: Point, z: f64) -> V3 { + let f = perspective_scale(self.eye, z); + V3((p.x - self.origin.x) / f, (p.y - self.origin.y) / f, z) + } /// The cosine between a face's outward unit normal `n` and the direction from `at` (both in /// view space) to the eye: positive when the face is turned towards the viewer. pub(super) fn facing(&self, at: V3, n: V3) -> f64 { @@ -271,14 +276,10 @@ impl<'a> Builder<'a> { /// The band between two partner rings (same length), as one quad per edge, or for a twisted /// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the /// direction (before rotation) the band faces away from the solid, for orienting normals. - pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> { - self.curved_band(a, b, cuts, outward, None, None) - } - - /// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the - /// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved. - /// With `side`, each quad carries where its corners lie on the side unrolled flat - /// ([`Facet::surface`]). + /// With `curves`, the pieces of curve the rings' edges follow and the outlines at `a` and `b`, + /// each quad keeps its edges along the profile curved. An edge cut into pieces is cut at points + /// of its curve, each piece taking an equal share of the edge's piece of curve. With `side`, + /// each quad carries where its corners lie on the side unrolled flat ([`Facet::surface`]). pub(super) fn curved_band( &mut self, a: &[V3], @@ -303,9 +304,31 @@ impl<'a> Builder<'a> { for i in 0..n { let j = (i + 1) % n; let pieces = cuts.get(i).copied().unwrap_or(1).max(1); + let span = curves.as_ref().and_then(|w| w.spans.get(i).copied().flatten()); + let places = curves.as_ref().map_or([None, None], |w| w.places); + // Where the edge's curve is at share `s` of it. + let t = |s: f64| span.map_or(0.0, |span| span.t0 + (span.t1 - span.t0) * s); + // A cut corner on a ring that follows a curve lies on the curve, moved by the offsets of + // the edge's corners from it (a bevel's miters), eased across the edge as the cap's edge + // eases them, so the pieces' edges follow the same curve as the cap's edge they meet. The + // offsets are eased as drawn, and the corner keeps the depth they give it in view space. + let camera = self.camera; + let corner = |p: V3, q: V3, s: f64, ring: usize| match (span, places.get(ring).copied().flatten()) { + (Some(span), Some(place)) if s > 0.0 && s < 1.0 => { + let (c, c0, c1) = (place(&span, t(s)), place(&span, span.t0), place(&span, span.t1)); + let (ep, eq) = (outline::fade(s), outline::fade(1.0 - s)); + let (dp, dq) = (p.sub(c0), q.sub(c1)); + let z = c.2 + dp.2 * ep + dq.2 * eq; + let (dp, dq) = (camera.project(p) - camera.project(c0), camera.project(q) - camera.project(c1)); + let v = camera.unproject(camera.project(c) + dp * ep + dq * eq, z); + if v.0.is_finite() && v.1.is_finite() && v.2.is_finite() { v } else { lerp(p, q, s) } + } + _ => lerp(p, q, s), + }; + let ends = [[self.camera.project(a[i]), self.camera.project(a[j])], [self.camera.project(b[i]), self.camera.project(b[j])]]; for k in 0..pieces { let (s0, s1) = (k as f64 / pieces as f64, (k + 1) as f64 / pieces as f64); - let quad = vec![lerp(a[i], a[j], s0), lerp(a[i], a[j], s1), lerp(b[i], b[j], s1), lerp(b[i], b[j], s0)]; + let quad = vec![corner(a[i], a[j], s0, 0), corner(a[i], a[j], s1, 0), corner(b[i], b[j], s1, 1), corner(b[i], b[j], s0, 1)]; // A twist bends the strip between two slices into a saddle: its normal is the whole // quad's average (Newell's), not one corner's triangle, which leans far to one side. let mut normal = newell(std::slice::from_ref(&quad)); @@ -343,10 +366,14 @@ impl<'a> Builder<'a> { }); } } - if let Some(w) = curves.as_mut().filter(|_| pieces == 1) - && let Some(span) = w.spans.get(i).copied().flatten() + if let Some(w) = curves.as_mut() + && let Some(span) = span { - self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, quad, w.near, w.far, w.budget))); + // An edge cut on its chord, with no place on the curve for its cut corners, + // stays straight. + let near = w.near.filter(|_| pieces == 1 || w.places[0].is_some()); + let far = w.far.filter(|_| pieces == 1 || w.places[1].is_some()); + self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, (t(s0), t(s1)), ends, quad, near, far, w.budget))); } } } @@ -397,9 +424,15 @@ pub(super) struct WallCurves<'a> { pub(super) spans: &'a [Option], pub(super) near: Option<&'a Along<'a>>, pub(super) far: Option<&'a Along<'a>>, + /// Where a point of a span's curve lies in view space on the band's two rings, for the corners + /// where a twisted wall's edge is cut ([`cuts`]). + pub(super) places: [Option<&'a Place<'a>>; 2], pub(super) budget: &'a mut Budget, } +/// Where the point at `t` on a span's curve lies in view space on one ring. +pub(super) type Place<'a> = dyn Fn(&Span, f64) -> V3 + 'a; + /// Where a band of the side lies on the side unrolled flat ([`super::side`]): the x of each end of /// each edge of its rings, and the y of its two rings. pub(super) struct SideBand<'a> { @@ -704,12 +737,19 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio // and within the sampling tolerance (which the inset rings themselves keep to) where it is. let sampled = (size / 2000.0).max(0.05); let maps: Vec = steps.iter().map(|s| Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, s.t), z(s.t))).collect(); - let at: Vec<_> = steps + let places: Vec<_> = steps .iter() .zip(&maps) .map(|(s, m)| { - let (w, camera) = (s.inset, &camera); - move |span: &Span, t: f64| camera.project(m.place(offset(span, t, w))) + let w = s.inset; + move |span: &Span, t: f64| m.place(offset(span, t, w)) + }) + .collect(); + let at: Vec<_> = places + .iter() + .map(|place| { + let camera = &camera; + move |span: &Span, t: f64| camera.project(place(span, t)) }) .collect(); // A step that is not inset moves the art point by point, affinely without perspective. @@ -762,10 +802,16 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio } else { 0.0 }; - // The edges a band shares with a cap follow the cap's curves; the edges between two bands - // stay straight, within the sampling tolerance. - let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len())); - let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget }); + // Each ring of a band follows the outline at its step: the edges a band shares with a cap + // follow the cap's curves, and an edge two bands share follows the same curves in both. + let place = |k: usize| places.get(k).map(|p| p as &Place); + let curves = Some(WallCurves { + spans: &traced.spans, + near: along.get(k), + far: along.get(k + 1), + places: [place(k), place(k + 1)], + budget: &mut budget, + }); let side = unrolled.and_then(|(_, x, y)| Some(SideBand { x, y: [*y.get(k)?, *y.get(k + 1)?] })); b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; } diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 812cf88a42..5826c28e6b 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -1,7 +1,8 @@ -use super::build::{Builder, Built, Camera, Keep, Order, Turn, check_bounds, cuts, fit, newell, outward}; +use super::build::{Builder, Built, Camera, Keep, Order, Place, Placing, Turn, WallCurves, check_bounds, cuts, fit, newell, outward}; use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material}; -use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings}; -use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, PlanarFace, Point, Rect, V3, Vec2, View}; +use super::outline::{self, Along, Budget, CURVE_TOLERANCE, EdgeCurve}; +use super::rings::{MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings_traced}; +use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, V3, Vec2, View}; /// The slices the sides are cut into: more to follow a twist or taper. fn slices(o: &Inflate) -> usize { @@ -11,6 +12,8 @@ fn slices(o: &Inflate) -> usize { /// A shape to inflate: its rings and the membrane under them on the grid of the bounds. struct Puff { rings: Vec>, + /// The rings with the piece of curve each edge follows. + traced: Vec, /// The index of the rings' edges. edges: Edges, cell: f64, @@ -50,7 +53,8 @@ fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result> = traced.iter().map(|r| r.points.clone()).collect(); if rings.is_empty() { return Ok(None); } @@ -73,7 +77,7 @@ fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result, before: usize, points: [Point; 3], center: fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Keep) -> Result { #[cfg(test)] INFLATED.with(|n| n.set(n.get() + 1)); - let Puff { rings, edges, cell, nx, ny, m, height } = p; + let Puff { rings, traced, edges, cell, nx, ny, m, height } = p; let outline: Vec<(Rect, vectorcraft_geom::SubPath)> = rings .iter() .filter_map(|r| { @@ -286,6 +294,58 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee let half = o.depth / 2.0; // The back: turned and scaled by the twist and taper, its puff too. let back_turn = Turn::new(bounds, o.twist, o.taper, 1.0); + // The outline of the front and the back where the surface meets it, through the art's curves: + // the cells' edges along it follow its curves within the sampling tolerance, as the cells' + // corners there lie on its sampled points and edges. + let mut budget = Budget::default(); + let sampled = (bounds.width().max(bounds.height()) / 2000.0).max(0.05); + let (front_map, back_map) = + (Placing::new(&camera, center, Turn::new(bounds, 0.0, 1.0, 0.0), half), Placing::new(&camera, center, back_turn, -half)); + let (front_at, back_at) = ( + |span: &Span, t: f64| camera.project(front_map.place(span.curve.eval(t))), + |span: &Span, t: f64| camera.project(back_map.place(span.curve.eval(t))), + ); + let (front_point, back_point) = (|p: Point| camera.project(front_map.place(p)), |p: Point| camera.project(back_map.place(p))); + let affine = camera.center_and_eye().1.is_none(); + let front_rim = Along { at: &front_at, map: Some(&front_point), affine, tolerance: sampled }; + let back_rim = Along { at: &back_at, map: Some(&back_point), affine, tolerance: sampled }; + // Where each ring's edges start among all the rings' edges, as the edge index counts them. + let starts: Vec = rings + .iter() + .scan(0usize, |s, r| { + let at = *s; + *s = s.saturating_add(r.len()); + Some(at) + }) + .collect(); + let rim_work = std::cell::Cell::new(MAX_RIM_WORK); + // The pieces of curve the edges of `pieces` (art points, lifted by `lifts`) follow where they + // lie along the outline: an edge whose two ends are on the outline, on one of its edges. + let rim = |pieces: &[Vec], lifts: &[Vec]| -> Vec>> { + pieces + .iter() + .zip(lifts) + .map(|(p, h)| { + let n = p.len(); + (0..n) + .map(|k| { + let (a, b) = (*p.get(k)?, *p.get((k + 1) % n)?); + if h.get(k).copied() != Some(0.0) || h.get((k + 1) % n).copied() != Some(0.0) { + return None; + } + let mut work = rim_work.get(); + let found = edges.holding(a, b, 1e-9, &mut work); + rim_work.set(work); + let (e, sa, sb) = found?; + let r = starts.partition_point(|s| *s <= e).checked_sub(1)?; + let span = traced.get(r)?.spans.get(e - starts.get(r)?)?.as_ref().copied()?; + let t = |s: f64| span.t0 + (span.t1 - span.t0) * s; + (sa != sb).then(|| (span, t(sa), t(sb))) + }) + .collect() + }) + .collect() + }; // The grid's cells, those the surface rises steeply across (near the outline) cut into // halves or quarters each way, so the steep rim is drawn in facets as fine as its curve. // Every corner sits on one fine lattice (a quarter cell), computed the same way wherever it @@ -477,7 +537,10 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee if let Some(triangles) = triangles { let order = if flat { Order::Last } else { Order::Depth }; for points in triangles { - let front = points.map(|q| camera.place(q, half + lift(q))); + let lifts = points.map(&lift); + let front: [V3; 3] = std::array::from_fn(|k| camera.place(points[k], half + lifts[k])); + let found = std::cell::OnceCell::new(); + let curves = || found.get_or_init(|| rim(&[points.to_vec()], &[lifts.to_vec()])); let before = b.facets.len(); let outward = newell(&[front.to_vec()]); if smoothed { @@ -485,11 +548,13 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee } else { b.face(vec![front.to_vec()], outward, order)?; } + b.outline(before, |c| outline::edges(c, curves(), &front_rim, &mut budget)); if o.map_surface { mark_surface(&mut b, before, points, center, outward, PlanarFace::Front); } if o.both_sides && o.cap { - let back = points.map(|q| camera.place(back_turn.apply(q), -half - lift(q) * back_turn.scale)); + let back: [V3; 3] = + std::array::from_fn(|k| camera.place(back_turn.apply(points[k]), -half - lifts[k] * back_turn.scale)); let before = b.facets.len(); let n = newell(&[back.to_vec()]); // The back winds the same way round as the front, so its outward @@ -506,6 +571,7 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee } else { b.face(vec![back.to_vec()], outward, order)?; } + b.outline(before, |c| outline::edges(c, curves(), &back_rim, &mut budget)); if o.map_surface { mark_surface(&mut b, before, points, center, outward, PlanarFace::Back); } @@ -521,7 +587,11 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee pieces.iter().zip(&lifts).map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(*q, half + h)).collect()).collect(); let n = newell(&front); let order = if flat { Order::Last } else { Order::Depth }; + let found = std::cell::OnceCell::new(); + let curves = || found.get_or_init(|| rim(&pieces, &lifts)); + let before = b.facets.len(); b.face(front, n, order)?; + b.outline(before, |c| outline::edges(c, curves(), &front_rim, &mut budget)); if o.both_sides && o.cap { // The back winds the same way round as the front, so its outward normal is // reversed. @@ -531,7 +601,9 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee .map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(back_turn.apply(*q), -half - h * back_turn.scale)).collect()) .collect(); let n = newell(&back); + let before = b.facets.len(); b.face(back, V3(-n.0, -n.1, -n.2), order)?; + b.outline(before, |c| outline::edges(c, curves(), &back_rim, &mut budget)); } } } @@ -541,7 +613,12 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee let back: Vec> = rings.iter().map(|r| r.iter().map(|p| camera.place(back_turn.apply(*p), -half)).collect()).collect(); // The back turned toward the viewer covers the walls it overlaps, even those nearer than // its center: twisted walls, and the walls of a fill inside the solid of its stroke. + let before = b.len(); b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)), Order::Last)?; + // The flat back is the art turned and scaled: its curves map exactly without perspective. + let along = Along { tolerance: CURVE_TOLERANCE, ..back_rim }; + let traced: Vec<&Ring> = traced.iter().collect(); + b.outline(before, |c| outline::face(&traced, c, &along, &mut budget)); } if o.depth > 0.0 { // The sides, cut into slices that follow a twist or taper. @@ -558,10 +635,45 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee if b.len().saturating_add(edges.saturating_mul(slices)) > MAX_SOLID_FACES { return Err(TOO_COMPLEX_SURFACE.into()); } - let sides = |b: &mut Builder<'_>, pieces: &[Vec]| -> Result<(), String> { - for (ring, pieces) in rings.iter().zip(pieces) { + // Each slice's ring follows the art's curves, turned and scaled, at its depth. + let maps: Vec = (0..=slices) + .map(|k| { + let t = k as f64 / slices as f64; + Placing::new(&camera, center, Turn::new(bounds, o.twist, o.taper, t), half - o.depth * t) + }) + .collect(); + let places: Vec<_> = maps.iter().map(|m| move |span: &Span, t: f64| m.place(span.curve.eval(t))).collect(); + let slice_at: Vec<_> = places + .iter() + .map(|place| { + let camera = &camera; + move |span: &Span, t: f64| camera.project(place(span, t)) + }) + .collect(); + let point_maps: Vec<_> = maps + .iter() + .map(|m| { + let camera = &camera; + move |p: Point| camera.project(m.place(p)) + }) + .collect(); + let along: Vec = slice_at + .iter() + .zip(&point_maps) + .map(|(at, map)| Along { at, map: Some(map as &dyn Fn(Point) -> Point), affine, tolerance: CURVE_TOLERANCE }) + .collect(); + let place = |k: usize| places.get(k).map(|p| p as &Place); + let sides = |b: &mut Builder<'_>, pieces: &[Vec], budget: &mut Budget| -> Result<(), String> { + for ((ring, traced), pieces) in rings.iter().zip(&traced).zip(pieces) { for k in 0..slices { - b.band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0))?; + let curves = WallCurves { + spans: &traced.spans, + near: along.get(k), + far: along.get(k + 1), + places: [place(k), place(k + 1)], + budget: &mut *budget, + }; + b.curved_band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0), Some(curves), None)?; } } Ok(()) @@ -578,11 +690,11 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee own_sides = Some((own, b.mesh.take())); } } - sides(&mut b, &pieces)?; + sides(&mut b, &pieces, &mut budget)?; if let Some((own, faces)) = own_sides { let mut m = Builder::new(&camera, o.cap, false, Keep::Faces); m.mesh = faces; - match sides(&mut m, &own) { + match sides(&mut m, &own, &mut budget) { Ok(()) => b.mesh = m.mesh, Err(_) => b.lose_mesh(), } diff --git a/crates/three-d/src/solid/membrane.rs b/crates/three-d/src/solid/membrane.rs index e8a855e29a..833b9de8a0 100644 --- a/crates/three-d/src/solid/membrane.rs +++ b/crates/three-d/src/solid/membrane.rs @@ -130,6 +130,27 @@ impl Edges { } } + /// The edge that both `a` and `b` lie on within `tolerance`: its index, counted through the + /// rings in order, and how far along it `a` and `b` lie (0 at its start, 1 at its end). Only the + /// bucket of the midpoint of `a` and `b` is looked in, and each edge looked at takes one from + /// `work`, which is not counted against the index's own budget: `None` once `work` is spent. + pub(super) fn holding(&self, a: Point, b: Point, tolerance: f64, work: &mut usize) -> Option<(usize, f64, f64)> { + let m = a.midpoint(b); + let (i, j) = (self.cell(m.x, self.origin.x), self.cell(m.y, self.origin.y)); + let bucket = self.buckets.get((j * self.n as isize + i) as usize)?; + for k in bucket { + *work = work.checked_sub(1)?; + let Some(&(p, q)) = self.edges.get(*k as usize) else { continue }; + let d = q - p; + if d.hypot2() < 1e-18 || segment_distance(a, p, q) > tolerance || segment_distance(b, p, q) > tolerance { + continue; + } + let along = |v: Point| ((v - p).dot(d) / d.hypot2()).clamp(0.0, 1.0); + return Some((*k as usize, along(a), along(b))); + } + None + } + /// Call `f` with each edge whose bounding box overlaps `r` (an edge in several of the /// buckets `r` covers comes more than once). fn each(&self, r: Rect, mut f: impl FnMut(Point, Point)) { diff --git a/crates/three-d/src/solid/outline.rs b/crates/three-d/src/solid/outline.rs index 93d9d70340..b2491896d7 100644 --- a/crates/three-d/src/solid/outline.rs +++ b/crates/three-d/src/solid/outline.rs @@ -2,7 +2,7 @@ //! wall along the profile follow the profile's curves as cubics, while each facet's polygon stays //! the shape that visibility and depth are worked out on. -use vectorcraft_geom::{BezPath, CubicBez, ParamCurve, PathData, Point}; +use vectorcraft_geom::{BezPath, CubicBez, ParamCurve, PathData, Point, Vec2}; use super::rings::{Ring, Span}; @@ -75,15 +75,54 @@ fn fit(g: &dyn Fn(f64) -> Point, p: Point, q: Point, a: f64, b: f64, tolerance: fit(g, p, m, a, mid, tolerance, depth + 1, out) && fit(g, m, q, mid, b, tolerance, depth + 1, out) } +/// How much of a corner's offset from the outline is left at share `x` of the way from the corner +/// to where the offset is eased out: 1 at the corner, 0 from 1 on, with no slope at either. +pub(super) fn fade(x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + 1.0 - x * x * (3.0 - 2.0 * x) +} + +/// 1 at `from`, 0 from `to` on ([`fade`] over `t`). +fn ease(t: f64, from: f64, to: f64) -> f64 { + if to == from { 1.0 } else { fade((t - from) / (to - from)) } +} + +/// The edge a piece of a wall's edge is cut from: its corners lie off the outline by `d.0` where +/// the edge starts on its span's curve (`t.0`) and by `d.1` where it ends (`t.1`). Each offset is +/// eased out across the whole edge, as a cap's edge eases it, so the pieces follow the cap's curve. +#[derive(Clone, Copy)] +struct Whole { + t: (f64, f64), + d: (Vec2, Vec2), +} + +impl Whole { + /// The outline at `t` on `span`'s curve, moved by the corners' offsets eased across the edge. + fn at(&self, step: &Along, span: &Span, t: f64) -> Point { + (step.at)(span, t) + self.d.0 * ease(t, self.t.0, self.t.1) + self.d.1 * ease(t, self.t.1, self.t.0) + } +} + /// The cubics from `p` to `q` along the piece of `span`'s curve from `t0` to `t1` at `step`, or /// `None` when they do not fit, or would take the budget past [`MAX_OUTLINE_CURVES`]. /// /// `p` and `q` are the face's own corners, which a bevel's miter can move off the curve's offset /// where the curve meets another edge at an angle. The difference is eased out from `p` by `fade.0` /// and into `q` from `fade.1` (the ends of the first and last sampled edge), as the face's polygon -/// does over those edges, so the curves meet the face's corners. +/// does over those edges, so the curves meet the face's corners. With `whole`, the piece is cut from +/// that edge, and the curve it follows is the whole edge's, with `p` and `q` measured from it. #[allow(clippy::too_many_arguments)] -fn piece(step: &Along, span: &Span, t0: f64, t1: f64, fade: (f64, f64), p: Point, q: Point, budget: &mut Budget) -> Option> { +fn piece( + step: &Along, + span: &Span, + t0: f64, + t1: f64, + fade: (f64, f64), + p: Point, + q: Point, + whole: Option, + budget: &mut Budget, +) -> Option> { if let Some(map) = step.map { let c = span.curve.subsegment(t0..t1); let c = CubicBez::new(p, map(c.p1), map(c.p2), q); @@ -94,13 +133,9 @@ fn piece(step: &Along, span: &Span, t0: f64, t1: f64, fade: (f64, f64), p: Point return (budget.0 <= MAX_OUTLINE_CURVES).then(|| vec![c]); } } - let (dp, dq) = (p - (step.at)(span, t0), q - (step.at)(span, t1)); - // 1 at the end, 0 from `to` on, with no slope at either. - let ease = |t: f64, from: f64, to: f64| { - let x = if to == from { 1.0 } else { ((t - from) / (to - from)).clamp(0.0, 1.0) }; - 1.0 - x * x * (3.0 - 2.0 * x) - }; - let g = |t: f64| (step.at)(span, t) + dp * ease(t, t0, fade.0) + dq * ease(t, t1, fade.1); + let base = |t: f64| whole.map_or_else(|| (step.at)(span, t), |w| w.at(step, span, t)); + let (dp, dq) = (p - base(t0), q - base(t1)); + let g = |t: f64| base(t) + dp * ease(t, t0, fade.0) + dq * ease(t, t1, fade.1); let mut out = vec![]; if !fit(&g, p, q, t0, t1, step.tolerance, 0, &mut out) { return None; @@ -141,7 +176,7 @@ fn contour(path: &mut BezPath, ring: &Ring, points: &[Point], step: &Along, budg (j, t1, last) = (j + 1, next.t1, next.t0); } let (p, q) = (points.get(i).copied().unwrap_or(first), end(j)); - match piece(step, &span, span.t0, t1, (span.t1, last), p, q, budget) { + match piece(step, &span, span.t0, t1, (span.t1, last), p, q, None, budget) { Some(curves) => { curved = true; for c in curves { @@ -173,11 +208,31 @@ pub(super) fn face(rings: &[&Ring], points: &[Vec], step: &Along, budget: /// The outline of a wall's quad `quad` (`a`, `a'`, `b'`, `b` projected: the edge at `near` from /// `a` to `a'`, then the edge at `far` back from `b'` to `b`), whose edges along the profile follow -/// `span`. An edge without its outline stays straight. `None` when neither edge is curved. -pub(super) fn wall(span: &Span, quad: &[Point], near: Option<&Along>, far: Option<&Along>, budget: &mut Budget) -> Option { +/// `span`'s curve from `t.0` to `t.1` (all of `span`, or the piece of it one cut of a twisted wall +/// takes). `ends` are the corners of the whole edges at `near` and at `far` (projected, where each +/// starts and ends on all of `span`), so that a piece follows the curve the whole edge does, as the +/// cap's edge it meets. An edge without its outline stays straight. `None` when neither edge is +/// curved. +#[allow(clippy::too_many_arguments)] +pub(super) fn wall( + span: &Span, + t: (f64, f64), + ends: [[Point; 2]; 2], + quad: &[Point], + near: Option<&Along>, + far: Option<&Along>, + budget: &mut Budget, +) -> Option { let [a, a2, b2, b] = <[Point; 4]>::try_from(quad).ok()?; - let front = near.and_then(|near| piece(near, span, span.t0, span.t1, (span.t1, span.t0), a, a2, budget)); - let back = far.and_then(|far| piece(far, span, span.t1, span.t0, (span.t0, span.t1), b2, b, budget)); + let (t0, t1) = t; + let whole = |step: &Along, [p, q]: [Point; 2]| { + let d = (p - (step.at)(span, span.t0), q - (step.at)(span, span.t1)); + let finite = [d.0, d.1].iter().all(|d| d.x.is_finite() && d.y.is_finite()); + finite.then_some(Whole { t: (span.t0, span.t1), d }) + }; + let [near_ends, far_ends] = ends; + let front = near.and_then(|near| piece(near, span, t0, t1, (t1, t0), a, a2, whole(near, near_ends), budget)); + let back = far.and_then(|far| piece(far, span, t1, t0, (t0, t1), b2, b, whole(far, far_ends), budget)); if front.is_none() && back.is_none() { return None; } @@ -195,3 +250,40 @@ pub(super) fn wall(span: &Span, quad: &[Point], near: Option<&Along>, far: Optio path.close_path(); Some(PathData::from_bezpath(&path)) } + +/// A piece of curve one edge of a face follows: the span, and the parameters on its curve where the +/// edge starts and ends. +pub(super) type EdgeCurve = (Span, f64, f64); + +/// The outline of a face whose contours `points` (projected) have some edges along pieces of curve: +/// `curves[c][k]` is the piece edge `k` of contour `c` follows, at `step`, or `None` for a straight +/// edge. `None` when no edge is curved. +pub(super) fn edges(points: &[Vec], curves: &[Vec>], step: &Along, budget: &mut Budget) -> Option { + if points.len() != curves.len() || curves.iter().flatten().all(Option::is_none) { + return None; + } + let mut path = BezPath::new(); + let mut curved = false; + for (points, curves) in points.iter().zip(curves) { + let n = points.len(); + let Some(&first) = points.first() else { continue }; + if curves.len() != n { + return None; + } + path.move_to(first); + for (k, c) in curves.iter().enumerate() { + let (p, q) = (points.get(k).copied().unwrap_or(first), points.get((k + 1) % n).copied().unwrap_or(first)); + match c.as_ref().and_then(|(span, t0, t1)| piece(step, span, *t0, *t1, (*t1, *t0), p, q, None, budget)) { + Some(cubics) => { + curved = true; + cubics.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)); + } + // The edge back to the first point is drawn by `close_path`. + None if k + 1 < n => path.line_to(q), + None => {} + } + } + path.close_path(); + } + curved.then(|| PathData::from_bezpath(&path)) +} diff --git a/crates/three-d/src/solid/rings.rs b/crates/three-d/src/solid/rings.rs index 882bd245af..195fe0039e 100644 --- a/crates/three-d/src/solid/rings.rs +++ b/crates/three-d/src/solid/rings.rs @@ -106,6 +106,7 @@ pub(super) const DEBRIS: f64 = 1e-6; /// contours were merged. An empty answer is an answer: contours that cancel (a square drawn twice /// under even-odd), or that are all thinner than [`DEBRIS`], fill nothing, so nothing is built. /// Each curve takes at most `most` pieces, on the profile as drawn and on the merged outline. +#[cfg(test)] pub(super) fn solid_rings(path: &PathData, rule: FillRule, size: f64, limit: usize, most: u32) -> Result>, String> { Ok(solid_rings_traced(path, rule, size, limit, most)?.into_iter().map(|r| r.points).collect()) } diff --git a/crates/three-d/src/solid/tests_curves.rs b/crates/three-d/src/solid/tests_curves.rs new file mode 100644 index 0000000000..4d00fe8353 --- /dev/null +++ b/crates/three-d/src/solid/tests_curves.rs @@ -0,0 +1,283 @@ +use vectorcraft_geom::{BezPath, CubicBez, FillRule, PathData, Point, Rect}; + +use super::build::Turn; +use super::*; + +fn shape(b: &BezPath) -> (PathData, Rect) { + let p = PathData::from_bezpath(b); + let r = p.bounds().unwrap(); + (p, r) +} + +/// Straight on, without perspective. +fn front() -> View { + View { rotation_x: 0.0, rotation_y: 0.0, rotation_z: 0.0, perspective: 0.0, ..View::default() } +} + +/// A circle of four cubics about `c`. +fn circle(c: Point, r: f64) -> BezPath { + let k = 0.552_284_749_830_793_6 * r; + let mut b = BezPath::new(); + b.move_to((c.x + r, c.y)); + b.curve_to((c.x + r, c.y + k), (c.x + k, c.y + r), (c.x, c.y + r)); + b.curve_to((c.x - k, c.y + r), (c.x - r, c.y + k), (c.x - r, c.y)); + b.curve_to((c.x - r, c.y - k), (c.x - k, c.y - r), (c.x, c.y - r)); + b.curve_to((c.x + k, c.y - r), (c.x + r, c.y - k), (c.x + r, c.y)); + b.close_path(); + b +} + +/// A "D" with its counter: straight stems, round bowls, and corners where they meet. +fn letter_d() -> BezPath { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((40.0, 0.0)); + b.curve_to((95.0, 0.0), (95.0, 100.0), (40.0, 100.0)); + b.line_to((0.0, 100.0)); + b.close_path(); + b.move_to((20.0, 20.0)); + b.line_to((20.0, 80.0)); + b.line_to((40.0, 80.0)); + b.curve_to((70.0, 80.0), (70.0, 20.0), (40.0, 20.0)); + b.close_path(); + b +} + +fn square(x: f64, y: f64, s: f64) -> BezPath { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + s, y)); + b.line_to((x + s, y + s)); + b.line_to((x, y + s)); + b.close_path(); + b +} + +/// A path's curved segments, segments and anchors. +fn anatomy(p: &PathData) -> [usize; 3] { + let mut n = [0; 3]; + for sp in &p.subpaths { + let count = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + n[0] += (0..count).filter(|i| !sp.segment_is_line(*i)).count(); + n[1] += count; + n[2] += sp.anchors.len(); + } + n +} + +/// A path's curved segments. +fn curves(p: &PathData) -> Vec { + let mut out = vec![]; + for sp in &p.subpaths { + let count = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + out.extend((0..count).filter(|i| !sp.segment_is_line(*i)).map(|i| sp.segment(i))); + } + out +} + +/// `b` flattened to within 1e-6 pt, each point moved by `map`. +fn fine(b: &BezPath, map: impl Fn(Point) -> Point) -> Vec> { + let mut out: Vec> = vec![]; + vectorcraft_geom::kurbo::flatten(b, 1e-6, |el| match el { + vectorcraft_geom::kurbo::PathEl::MoveTo(p) => out.push(vec![map(p)]), + vectorcraft_geom::kurbo::PathEl::LineTo(p) => out.last_mut().into_iter().for_each(|r| r.push(map(p))), + _ => {} + }); + out +} + +/// How far `c` lies from the polygons `target` at most, at 33 points along it. +fn farthest(c: &CubicBez, target: &[Vec]) -> f64 { + (0..=32).map(|k| edge_distance(target, c.eval(f64::from(k) / 32.0))).fold(0.0, f64::max) +} + +/// A rounded bevel on both sides steps through many rings between the caps. Every edge along the +/// art's curves, between two bevel steps or two wall slices as well as at a cap, is a cubic: each +/// side facet that follows a curve has both its edges curved, four anchors, and lies within the +/// sampling tolerance of its own polygon. Two visible facets on either side of one ring draw the +/// edge they share as the same curve. +#[test] +fn interior_bevel_edges_keep_the_curves_of_the_art() { + for art in [circle(Point::new(50.0, 50.0), 40.0), letter_d()] { + let (p, b) = shape(&art); + let bevel = Bevel { shape: BevelShape::Rounded, inside: true, width: 4.0, height: 4.0, both_sides: true, ..Bevel::default() }; + let o = Extrude { depth: 50.0, bevel: Some(bevel), ..Extrude::default() }; + let f = extrude(&p, FillRule::EvenOdd, b, o, View { rotation_x: 20.0, rotation_y: 30.0, ..front() }).unwrap(); + let sides: Vec<&Facet> = f.iter().filter(|f| f.side && f.outline.is_some()).collect(); + assert!(sides.len() > 40, "{}", sides.len()); + for side in &sides { + let path = side.path(); + assert_eq!(anatomy(&path), [2, 4, 4], "{path:?}"); + for c in curves(&path) { + assert!(farthest(&c, &side.contours) <= 2.0 * 0.05, "{c:?}"); + } + } + let all: Vec<(usize, CubicBez)> = sides.iter().enumerate().flat_map(|(k, f)| curves(&f.path()).into_iter().map(move |c| (k, c))).collect(); + let mut shared = 0; + for (k, c) in &all { + for (_, d) in all.iter().filter(|(j, d)| j != k && d.p0.distance(c.p3) < 1e-9 && d.p3.distance(c.p0) < 1e-9) { + shared += 1; + let far = (0..=16).map(|u| c.eval(f64::from(u) / 16.0).distance(d.eval(1.0 - f64::from(u) / 16.0))).fold(0.0, f64::max); + assert!(far <= 1e-6, "{far}"); + } + } + assert!(shared > 20, "{shared}"); + } +} + +/// A twist cuts each edge of a wall into pieces at points of the art's curve: every piece keeps +/// both its edges curved, and the pieces at the front draw the cap's edge, within 0.001 pt of the +/// cap's curves without perspective and twice that with it. +#[test] +fn a_twisted_wall_keeps_curves_where_a_twist_cuts_it() { + let art = circle(Point::new(50.0, 50.0), 40.0); + let (p, b) = shape(&art); + // Shallow, so that each slice of the wall is narrower than its edges are long. + let o = Extrude { depth: 2.0, twist: 30.0, ..Extrude::default() }; + let turned = View { rotation_x: 20.0, rotation_y: 30.0, ..front() }; + for (view, tolerance) in [(turned, outline::CURVE_TOLERANCE), (View { perspective: 60.0, ..turned }, 2.0 * outline::CURVE_TOLERANCE)] { + let f = extrude(&p, FillRule::EvenOdd, b, o, view).unwrap(); + let cap = f.iter().find(|f| f.depth == f64::MAX).unwrap(); + let corners: Vec = cap.contours.iter().flatten().copied().collect(); + let cap = fine(&cap.path().to_bezpath(), |q| q); + let sides: Vec<&Facet> = f.iter().filter(|f| f.side).collect(); + assert!(sides.len() > 64, "{}", sides.len()); + let (mut at_cap, mut cut) = (0, 0); + for side in &sides { + let path = side.path(); + assert_eq!(anatomy(&path), [2, 4, 4], "{path:?}"); + // The cap's curves are fitted within the curve tolerance in perspective. + for c in curves(&path).iter().filter(|c| edge_distance(&cap, c.p0) <= tolerance && edge_distance(&cap, c.p3) <= tolerance) { + at_cap += 1; + // A piece that starts or ends where the twist cuts the edge, between two of the + // cap's sampled points. + if [c.p0, c.p3].iter().any(|q| corners.iter().all(|v| v.distance(*q) > 1e-6)) { + cut += 1; + } + let far = farthest(c, &cap); + assert!(far <= tolerance + 1e-6, "{far}"); + } + } + assert!(at_cap > 10 && cut > 5, "{at_cap} at the cap, {cut} of them cut"); + } +} + +/// A half disc: a straight diameter and a round arc, meeting it at right angles. +fn half_disc() -> BezPath { + let k = 0.552_284_749_830_793_6 * 50.0; + let mut b = BezPath::new(); + b.move_to((0.0, 50.0)); + b.line_to((100.0, 50.0)); + b.curve_to((100.0, 50.0 - k), (50.0 + k, 0.0), (50.0, 0.0)); + b.curve_to((50.0 - k, 0.0), (0.0, 50.0 - k), (0.0, 50.0)); + b.close_path(); + b +} + +/// With a bevel, the cap is inset, and its corners where the arc meets the diameter at a right +/// angle lie off the curve's inset by the miter. A twist cuts the band next to the cap into pieces: +/// the pieces that start or end at one of the cap's corners draw the cap's edge, within the cap's +/// sampling tolerance of its curves, with no gap where they meet it. +#[test] +fn twisted_bevel_pieces_meet_the_cap_at_sharp_joins() { + let (p, b) = shape(&half_disc()); + let bevel = Bevel { inside: true, width: 4.0, height: 1.0, ..Bevel::default() }; + let o = Extrude { depth: 4.0, twist: 30.0, bevel: Some(bevel), ..Extrude::default() }; + let turned = View { rotation_x: 20.0, rotation_y: 30.0, ..front() }; + for view in [turned, View { perspective: 60.0, ..turned }] { + let f = extrude(&p, FillRule::EvenOdd, b, o, view).unwrap(); + let cap = f.iter().find(|f| f.depth == f64::MAX).unwrap(); + let corners: Vec = cap.contours.iter().flatten().copied().collect(); + let cap = fine(&cap.path().to_bezpath(), |q| q); + let mut pieces = 0; + for side in f.iter().filter(|f| f.side) { + for c in curves(&side.path()) { + let at_corner = |q: Point| corners.iter().any(|v| v.distance(q) < 1e-6); + // One end at a corner of the cap, the other where the twist cuts the edge. + if at_corner(c.p0) == at_corner(c.p3) { + continue; + } + pieces += 1; + let far = farthest(&c, &cap); + assert!(far <= 2.0 * 0.05 + 1e-6, "{far}: {c:?}"); + } + } + assert!(pieces > 10, "{pieces}"); + } +} + +/// Inflate keeps the art's curves where its faces meet the outline: the flat back is the art +/// turned, one cubic for each of its curves within 0.001 pt; every side facet has both its edges +/// curved; and the front's cells along the outline are curved there, within the sampling +/// tolerance of the art. +#[test] +fn inflate_keeps_the_curves_of_its_outline() { + let art = circle(Point::new(50.0, 50.0), 40.0); + let (p, b) = shape(&art); + let o = Inflate { depth: 20.0, twist: 30.0, ..Inflate::default() }; + let behind = View { rotation_y: 180.0, ..front() }; + let f = inflate(&p, FillRule::EvenOdd, b, o, behind).unwrap(); + let back = f.iter().find(|f| f.depth == f64::MAX).unwrap().path(); + assert_eq!(anatomy(&back), [4, 4, 4], "{back:?}"); + let camera = Camera::new(behind, b, 1.0); + let turn = Turn::new(b, o.twist, o.taper, 1.0); + let target = fine(&art, |q| camera.project(camera.place(turn.apply(q), -o.depth / 2.0))); + for c in curves(&back) { + assert!(farthest(&c, &target) <= outline::CURVE_TOLERANCE + 1e-6, "{c:?}"); + } + + for (o, view) in [ + (o, View { rotation_x: 20.0, rotation_y: 30.0, ..front() }), + (Inflate { both_sides: true, map_surface: true, ..o }, View { rotation_x: 20.0, rotation_y: 30.0, perspective: 60.0, ..front() }), + ] { + let f = inflate(&p, FillRule::EvenOdd, b, o, view).unwrap(); + let sides: Vec<&Facet> = f.iter().filter(|f| f.side).collect(); + assert!(!sides.is_empty()); + assert!(sides.iter().all(|f| anatomy(&f.path())[..2] == [2, 4]), "a side facet with a straight edge along the circle"); + let rim: Vec<&Facet> = f.iter().filter(|f| !f.side && f.outline.is_some()).collect(); + assert!(rim.len() > 20, "{}", rim.len()); + } + + // Seen straight on, the front's curved edges are the art's circle. + let f = inflate(&p, FillRule::EvenOdd, b, Inflate::default(), front()).unwrap(); + let rim: Vec = f.iter().filter(|f| f.outline.is_some()).flat_map(|f| curves(&f.path())).collect(); + assert!(rim.len() > 20, "{}", rim.len()); + let circle = fine(&art, |q| q); + for c in &rim { + assert!(farthest(c, &circle) <= 0.05 + 1e-6, "{c:?}"); + } +} + +/// A shape of straight edges gets no curves; a tiny circle and a twisted, tapered Inflate keep +/// theirs without points that are not finite. +#[test] +fn straight_tiny_and_twisted_solids_keep_their_curves_bounded() { + let (p, b) = shape(&square(0.0, 0.0, 100.0)); + let bevel = Bevel { shape: BevelShape::Rounded, inside: true, width: 4.0, height: 4.0, both_sides: true, ..Bevel::default() }; + let view = View { rotation_x: 20.0, rotation_y: 30.0, ..front() }; + let f = extrude(&p, FillRule::EvenOdd, b, Extrude { depth: 50.0, twist: 45.0, bevel: Some(bevel), ..Extrude::default() }, view).unwrap(); + assert!(f.iter().all(|f| f.outline.is_none())); + let f = inflate(&p, FillRule::EvenOdd, b, Inflate { depth: 20.0, ..Inflate::default() }, view).unwrap(); + assert!(f.iter().all(|f| f.outline.is_none())); + + let tiny = PathData::from_bezpath(&circle(Point::new(1.0, 1.0), 0.01)); + let b = tiny.bounds().unwrap(); + for f in [ + extrude( + &tiny, + FillRule::NonZero, + b, + Extrude { depth: 0.02, twist: 90.0, bevel: Some(Bevel { width: 0.002, height: 0.002, ..bevel }), ..Extrude::default() }, + view, + ), + inflate(&tiny, FillRule::NonZero, b, Inflate { depth: 0.02, twist: 360.0, taper: 0.01, both_sides: true, ..Inflate::default() }, view), + ] { + let f = f.unwrap(); + assert!(f.iter().any(|f| !curves(&f.path()).is_empty()), "no curve on a tiny circle"); + for f in f { + for c in curves(&f.path()) { + assert!([c.p0, c.p1, c.p2, c.p3].iter().all(|q| q.x.is_finite() && q.y.is_finite()), "{c:?}"); + } + } + } +} diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index b484651181..7124f55cda 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -11,8 +11,9 @@ //! the side the path bends toward; with Shift held at the press, on the other side. On a straight //! stretch, at a cusp, at a corner, or where the circle would reach past the canvas, the pointer //! shows "Straight segment", "Cusp", "Corner" or "Circle too large" instead, and a click draws -//! nothing. The pointer passes over the circles the tool drew until another tool is chosen or an -//! edit, Undo or Redo is made outside the tool. +//! nothing. The pointer passes over the circles the tool drew until the selection holds none of +//! them, another tool is chosen, another document becomes active, or an edit, Undo or Redo is +//! made outside the tool. use std::collections::HashSet; @@ -58,10 +59,24 @@ pub struct CurvatureCircleTool { /// The press in progress, where the pointer was pressed: what a release draws. press: Option<(Hit, bool)>, from: Point, - /// The circles the tool drew since the history last moved outside it. + /// The circles the tool drew since the history last moved outside it or the selection last + /// held none of them. drawn: HashSet, } +impl CurvatureCircleTool { + /// After Deselect or a selection made outside the tool, the selection holds none of the + /// circles the tool drew, and the pointer reaches them again. + /// Returns whether it forgot any. + fn forget_unselected(&mut self, cx: &ToolContext) -> bool { + if self.drawn.is_empty() || cx.selection.objects.iter().any(|id| self.drawn.contains(id)) { + return false; + } + self.drawn.clear(); + true + } +} + /// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in /// `skip` left out; of paths at the same distance, a selected one, then the one on top. fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { @@ -118,6 +133,7 @@ impl Tool for CurvatureCircleTool { if !ev.pos.is_finite() { return vec![]; } + self.forget_unselected(cx); match ev.kind { PointerKind::Move => { self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); @@ -185,6 +201,16 @@ impl Tool for CurvatureCircleTool { } } + /// A command from outside the tool (Deselect, a pick in the Layers panel) may leave none of the + /// circles the tool drew selected. The circle shown under the pointer then waits for the next + /// hover. + fn after_command(&mut self, cx: &ToolContext) -> Vec { + if self.forget_unselected(cx) { + self.hover = None; + } + vec![] + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.hover = None; self.press = None; diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs index d417af58dc..1dccebecc6 100644 --- a/crates/tools/src/curvature_circle/tests.rs +++ b/crates/tools/src/curvature_circle/tests.rs @@ -198,6 +198,27 @@ fn the_next_click_passes_over_the_circle_just_drawn() { assert_eq!(params(&click(&mut t, &cx, (302.0, 200.0), Mods::default()))["id"], json!(drawn.0)); } +/// Once the selection holds none of the circles the tool drew (after Deselect, or a pick of another +/// object), the pointer reaches them again. +#[test] +fn a_selection_without_the_drawn_circles_makes_them_reachable() { + let line = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 450 L400 450").unwrap()); + let d = doc_with(&[circle(), circle(), line]); + let ids: Vec = d.layers[0].children().unwrap().iter().rev().map(|n| n.id).collect(); + let (drawn, under, other) = (ids[0], ids[1], ids[2]); + let p = paint(); + let holding = Selection { objects: vec![drawn], ..Selection::default() }; + let both = Selection { objects: vec![drawn, other], ..Selection::default() }; + let none = Selection::default(); + let picked = Selection { objects: vec![other], ..Selection::default() }; + for (after, want) in [(&holding, under), (&both, under), (&none, drawn), (&picked, drawn)] { + let mut t = CurvatureCircleTool::default(); + t.notify(&ToolContext { smart_guides: false, ..cx(&d, &holding, &p) }, "created"); + let cx = ToolContext { smart_guides: false, ..cx(&d, after, &p) }; + assert_eq!(params(&click(&mut t, &cx, (302.0, 200.0), Mods::default()))["id"], json!(want.0), "{:?}", after.objects); + } +} + /// A press that a second finger or a canceled touch drops draws nothing on the release, and an /// edit made outside the tool drops what the pointer was over. #[test] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index dffe13a378..9568668c53 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -106,6 +106,12 @@ pub struct DimensionTool { /// The document's next object id at the dimension's first preview: the id its preview takes /// (`dimension.create` gives the dimension the next id). The preview is not a level. preview_id: u64, + /// The dimension drawn already under the press under way, when a drag from there moves it + /// ([`dimension_under`]). + grab: Option, + /// While a dimension drawn already is dragged: its id, where the press was and its recipe + /// then. `pending` holds it where the pointer puts it. + moving: Option<(NodeId, Point, Dimension)>, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -151,6 +157,11 @@ fn constrained(cx: &ToolContext, last: Point, at: Point) -> Point { /// Nearest editable segment, with bounded work and no snapping to dimension artwork itself. pub fn pick(cx: &ToolContext, p: Point) -> Option { + pick_among(cx, p, cx.doc.layers.iter().rev().map(|n| n.as_ref())) +} + +/// [`pick`] among `roots`, topmost first, and what they hold. +fn pick_among<'a>(cx: &ToolContext, p: Point, roots: impl Iterator) -> Option { let mut best = None; let mut dist = cx.tol(8.0); let mut budget = 20_000usize; @@ -180,7 +191,7 @@ pub fn pick(cx: &ToolContext, p: Point) -> Option { } } } - for n in cx.doc.layers.iter().rev() { + for n in roots { visit(n, p, &mut budget, &mut dist, &mut best); } best @@ -536,6 +547,117 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false))) } +/// The dimension drawn already that a drag from `p` moves, and how far `p` lies from its lines +/// and label (0 inside the label's bounds): the dimension holding the topmost object the canvas +/// hits within 8 pixels of `p`, when it can be edited. The hit takes in what the dimension paints +/// (stroke widths and arrowheads), the clipping masks over it and isolation mode. A dimension that +/// a geometry effect on it, on a part of it or on a group around it draws elsewhere is not taken +/// where effects are drawn. +fn dimension_under(cx: &ToolContext, p: Point) -> Option<(NodeId, f64)> { + use vectorcraft_geom::kurbo::ParamCurveNearest; + fn art(n: &Node, p: Point, budget: &mut usize, near: &mut f64) { + if *budget == 0 || !n.visible { + return; + } + *budget -= 1; + if let NodeKind::Text(_) = &n.kind + && let Some(r) = n.geometric_bounds() + { + let (dx, dy) = ((r.x0 - p.x).max(p.x - r.x1).max(0.0), (r.y0 - p.y).max(p.y - r.y1).max(0.0)); + *near = near.min(dx.hypot(dy)); + } + if let Some(path) = n.path_data() { + for sp in &path.subpaths { + for i in 0..sp.segment_count() { + if *budget == 0 { + return; + } + *budget -= 1; + let d = sp.segment(i).nearest(p, 1e-4).distance_sq.sqrt(); + if d.is_finite() { + *near = near.min(d); + } + } + } + } + for c in n.children().into_iter().flatten() { + art(c, p, budget, near); + } + } + if !cx.doc.dimensions { + return None; + } + let opt = vectorcraft_doc::hit::HitOptions { tol: cx.tol(8.0), ..cx.hit_options() }; + let hit = vectorcraft_doc::hit::hit_test(cx.doc, p, opt)?; + let chain: Vec = hit.ancestry.iter().copied().chain([hit.leaf]).collect(); + // The innermost dimension holding the object hit: the one that draws it. + let at = chain.iter().rposition(|id| cx.doc.node(*id).is_some_and(|n| n.extras().dimension.is_some()))?; + let id = *chain.get(at)?; + // In isolation mode only a dimension at or inside the isolated object is moved: one around an + // isolated part of it is outside the editing scope. + let scope_at = opt.scope.and_then(|s| chain.iter().position(|a| *a == s)); + if scope_at.is_some_and(|i| i > at) { + return None; + } + // Where a geometry effect on the dimension, on a part of it or on a group around it draws it is + // not where its recipe puts it, so a drag there could not follow the pointer. In outline, and + // below a layer whose Preview is off, the canvas draws no effects and the recipe is what it + // hits. + let nodes: Vec<&Node> = chain.iter().filter_map(|id| cx.doc.node(*id)).collect(); + let below = scope_at.map_or(0, |i| i + 1); + let outline = opt.outline || nodes.iter().skip(below).any(|n| matches!(n.kind, NodeKind::Layer { preview: false, .. })); + let item_geometry = |n: &Node| n.appearance.items.iter().any(|item| item.visible() && vectorcraft_effects::has_geometry(item.effects())); + let displaced = nodes.iter().enumerate().any(|(i, n)| vectorcraft_effects::has_geometry(&n.appearance.effects) || (i >= at && item_geometry(n))); + // The parts of the dimension the press did not land on count too: a geometry effect on any of + // them is drawn elsewhere as well. + let parts_displaced = cx.doc.node(id).is_some_and(|d| { + d.try_walk(&mut |n| { + if vectorcraft_effects::has_geometry(&n.appearance.effects) || item_geometry(n) { + std::ops::ControlFlow::Break(()) + } else { + std::ops::ControlFlow::Continue(()) + } + }) + .is_break() + }); + if !outline && (displaced || parts_displaced) { + return None; + } + let n = cx.doc.node(id).filter(|_| cx.doc.is_editable(id))?; + let (mut budget, mut near) = (20_000usize, f64::INFINITY); + art(n, p, &mut budget, &mut near); + Some((id, near)) +} + +/// Where [`Dimension::place`] puts dimension `d`, grabbed at `start`, for the pointer at `p`: the +/// line of a linear dimension moves as far across as the pointer moved, the arc of an angular one +/// grows or shrinks by as much as the pointer moved away from or toward the vertex, and a radius +/// or diameter line turns about the center by the angle the pointer turned through, so the part +/// grabbed stays under the pointer wherever it was grabbed. +fn grabbed_to(d: &Dimension, start: Point, p: Point) -> Point { + let handle = d.handle(); + match d.mode { + DimensionMode::Linear => handle + (p - start), + DimensionMode::Angular => { + let out = handle - d.vertex; + let r = out.hypot() + p.distance(d.vertex) - start.distance(d.vertex); + if out.hypot() > 1e-9 { d.vertex + out / out.hypot() * r.max(12.0) } else { handle } + } + DimensionMode::Radius | DimensionMode::Diameter => { + let (from, to) = (start - d.a, p - d.a); + if to.hypot() <= 1e-9 { + return handle; + } + // Grabbed at the center: the line turns toward the pointer. + if from.hypot() <= 1e-9 { + return p; + } + let v = handle - d.a; + d.a + Vec2::from_angle(v.atan2() + to.atan2() - from.atan2()) * v.hypot() + } + } +} + /// The line of a linear dimension already drawn: its ends and its direction. type DimensionLine = ((Point, Point), Vec2); @@ -576,7 +698,10 @@ fn dimension_lines(doc: &vectorcraft_doc::Document, preview: (u64, [Point; 2])) /// Where the line of the linear dimension `d`, placed through `p`, lands on the level of one of /// the `levels` that runs parallel to it, within `reach` of `p` across the line: the point to /// place `d` through, and the ends of that other line. The nearest level wins, then the line -/// nearest `p` along it (none nearer than a line that `p` lies across). +/// nearest `p` along it (none nearer than a line that `p` lies across). A line runs parallel when +/// it moves off its level by no more than 1e-6 pt across the span that both lines cover, so a line +/// at a slight angle to `d` is not a level however near its first end lies. A level that would put +/// the line past the limits a dimension allows is passed over. fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> Option<(Point, (Point, Point))> { if d.mode != DimensionMode::Linear { return None; @@ -584,14 +709,21 @@ fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> let (u, normal) = (d.direction(), d.normal()); let mut best: Option<(f64, f64, f64, (Point, Point))> = None; for &(ends, direction) in levels { - if u.cross(direction).abs() > 1e-6 { + let along_u = [ends.0, ends.1, d.a, d.b].map(|q| (q - ends.0).dot(u)); + let span = along_u.iter().fold(f64::NEG_INFINITY, |m, s| m.max(*s)) - along_u.iter().fold(f64::INFINITY, |m, s| m.min(*s)); + let drift = u.cross(direction).abs() * span; + if !drift.is_finite() || drift > 1e-6 { continue; } let shift = (ends.0 - p).dot(normal); let (s0, s1) = ((ends.0 - p).dot(u), (ends.1 - p).dot(u)); let along = if s0 * s1 <= 0.0 { 0.0 } else { s0.abs().min(s1.abs()) }; if shift.is_finite() && along.is_finite() && shift.abs() <= reach && best.is_none_or(|(s, a, _, _)| (shift.abs(), along) < (s, a)) { - best = Some((shift.abs(), along, shift, ends)); + let mut placed = d.clone(); + placed.place(p + normal * shift); + if placed.validate().is_ok() { + best = Some((shift.abs(), along, shift, ends)); + } } } best.map(|(_, _, shift, ends)| (p + normal * shift, ends)) @@ -816,6 +948,9 @@ impl DimensionTool { p } fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec { + if self.moving.is_some() { + return self.reposition(cx, p); + } self.level_guide = None; let Some(d) = &mut self.pending else { return vec![] }; if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) @@ -856,15 +991,10 @@ impl DimensionTool { if !self.began { self.preview_id = cx.doc.peek_next_id(); } - let (from, at) = match cx.interaction_doc { - Some(began) => (began, (cx.revision.0, 0, std::ptr::from_ref(began).addr())), - None => (cx.doc, (cx.revision.0, cx.revision.1, 0)), - }; - if !self.began || (cx.smart_guides && self.levels_at != at) { - self.levels = dimension_lines(from, (self.preview_id, [d.a, d.b])); - self.levels_at = at; - } + let points = [d.a, d.b]; + self.read_levels(cx, (self.preview_id, points)); } + let Some(d) = &mut self.pending else { return vec![] }; let level = if cx.smart_guides { line_level(&self.levels, d, p, cx.snap_tol()) } else { None }; d.place(level.map_or(p, |(on_level, _)| on_level)); if d.validate().is_err() { @@ -879,6 +1009,51 @@ impl DimensionTool { actions.push(Action::Preview("dimension.create".into(), Self::params(d))); actions } + /// Reads `levels` at the first preview and, with Smart Guides on, again when the document they + /// come from has changed since: while an interaction is in progress, the document as it began. + /// `skip` names the dimension being placed or moved, which is not a level: its id and the + /// points it measures. + fn read_levels(&mut self, cx: &ToolContext, skip: (u64, [Point; 2])) { + let (from, at) = match cx.interaction_doc { + Some(began) => (began, (cx.revision.0, 0, std::ptr::from_ref(began).addr())), + None => (cx.doc, (cx.revision.0, cx.revision.1, 0)), + }; + if !self.began || (cx.smart_guides && self.levels_at != at) { + self.levels = dimension_lines(from, skip); + self.levels_at = at; + } + } + /// Moves the dimension drawn already that a drag picked up ([`Self::moving`]) as + /// [`grabbed_to`] says, and what it measures stays. With Smart Guides on, a linear + /// dimension's line lands on the level of a parallel dimension line, as when it is placed. + fn reposition(&mut self, cx: &ToolContext, p: Point) -> Vec { + self.level_guide = None; + let Some((id, start, from)) = self.moving.clone() else { return vec![] }; + let at = grabbed_to(&from, start, p); + if from.mode == DimensionMode::Linear { + self.read_levels(cx, (id.0, [from.a, from.b])); + } + // The levels are measured across from the line through `at` and, along it, from the + // pointer, which may be far from the line's middle. + let dir = from.direction(); + let along = at + dir * (p - at).dot(dir); + let level = if cx.smart_guides { line_level(&self.levels, &from, along, cx.snap_tol()) } else { None }; + let at = level.map_or(at, |(on_level, _)| on_level); + let mut d = from; + d.place(at); + if d.validate().is_err() { + return vec![]; + } + self.pending = Some(d); + self.level_guide = level.map(|(_, ends)| ends); + let mut actions = vec![]; + if !self.began { + actions.push(Action::Begin("Update Dimensions".into())); + self.began = true; + } + actions.push(Action::Preview("dimension.update".into(), json!({"ids":[id.0],"at":[at.x,at.y]}))); + actions + } /// Places the pending dimension at `p` and commits it. fn place(&mut self, cx: &ToolContext, p: Point) -> Vec { let mut out = self.preview(cx, p); @@ -906,6 +1081,8 @@ impl DimensionTool { self.second = None; self.level_guide = None; self.levels.clear(); + self.grab = None; + self.moving = None; } /// A plain click: picks a point or a line, or measures a circle's radius. fn click(&mut self, cx: &ToolContext, p: Point, target: Option, mods: Mods) -> Vec { @@ -1038,13 +1215,42 @@ impl Tool for DimensionTool { && (anchor_under(cx, ev.pos).is_some() || preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); - self.press = Some((ev.pos, self.target(cx, ev.pos))); + let target = self.target(cx, ev.pos); + // A press on a dimension drawn already, nearer to its lines and label than to any + // segment of the art, moves that dimension when it drags. A click there still + // picks a point. + self.grab = None; + if self.points.is_empty() + && self.lines.is_empty() + && let Some((id, d)) = dimension_under(cx, ev.pos) + { + // In isolation mode only art inside the isolated object competes for the press. + let edge = match cx.hit_options().scope.and_then(|s| cx.doc.node(s)) { + Some(isolated) => pick_among(cx, ev.pos, std::iter::once(isolated)), + None => pick(cx, ev.pos), + }; + let art = edge.and_then(|e| nearest_on(cx, &e, ev.pos)).map(|q| q.distance(ev.pos)); + if art.is_none_or(|a| d < a) { + self.grab = Some(id); + } + } + self.press = Some((ev.pos, target)); vec![] } PointerKind::Drag => { if self.pending.is_some() && !self.dragging && self.press.is_some() { return self.preview(cx, ev.pos); } + if self.pending.is_none() + && let (Some((start, _)), Some(id)) = (self.press.as_ref(), self.grab) + && start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 }) + && let Some(d) = cx.doc.node(id).and_then(|n| n.extras().dimension.as_deref()) + { + self.moving = Some((id, *start, d.clone())); + self.pending = Some(d.clone()); + self.dragging = true; + self.grab = None; + } if self.pending.is_none() && let Some((start, Some(target))) = self.press.clone() && start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 }) @@ -1169,8 +1375,9 @@ impl Tool for DimensionTool { out.extend(self.snap.guides().iter().cloned()); } // A dimension line placed on the level of another: one alignment guide across both lines, - // unless Alignment Guides are off. - if cx.alignment_guides + // unless Smart Guides or Alignment Guides are off. + if cx.smart_guides + && cx.alignment_guides && let (Some(d), Some((c, e))) = (&self.pending, self.level_guide) { let (a, b) = d.line_ends(); @@ -1235,6 +1442,79 @@ mod tests { } } + /// A line at a slight angle is not a level, even where its first end lies within reach across + /// the line: it moves off the level by 9 pt across the span. A line exactly parallel is. + #[test] + fn a_line_at_a_slight_angle_is_not_a_level() { + let pt = Point::new; + let d = + DimensionTool::default().recipe(DimensionMode::Linear, pt(10_000_050.0, 200.0), pt(10_000_150.0, 200.0), pt(10_000_100.0, 200.0), None); + let (from, to) = (pt(100.0, 170.0), pt(10_000_100.0, 179.0)); + let slanted = ((from, to), (to - from) / (to - from).hypot()); + assert!(line_level(&[slanted], &d, pt(10_000_100.0, 168.0), 4.0).is_none()); + let parallel = ((from, pt(10_000_100.0, 170.0)), Vec2::new(1.0, 0.0)); + let (at, _) = line_level(&[parallel], &d, pt(10_000_100.0, 168.0), 4.0).expect("on the level"); + assert!(at.distance(pt(10_000_100.0, 170.0)) < 1e-9, "{at:?}"); + } + + /// The span a level is checked across runs from the lowest to the highest point of both lines + /// along the dimension, whichever end of the other line comes first, and has no lower bound. + #[test] + fn a_level_is_checked_across_the_whole_span_of_both_lines() { + let pt = Point::new; + let level = |from: Point, to: Point| ((from, to), (to - from) / (to - from).hypot()); + // 0.00000075 pt off across 100 pt drifts 0.0000015 pt across the 200 pt both lines cover. + let d = DimensionTool::default().recipe(DimensionMode::Linear, pt(-100.0, 200.0), pt(100.0, 200.0), pt(0.0, 200.0), None); + let (a, b) = (pt(0.0, 170.0), pt(100.0, 170.000_000_75)); + for slanted in [level(a, b), level(b, a)] { + assert!(line_level(&[slanted], &d, pt(0.0, 168.0), 4.0).is_none(), "{slanted:?}"); + } + // 0.0000005 pt off across the 0.1 pt both lines cover is within the tolerance. + let d = DimensionTool::default().recipe(DimensionMode::Linear, pt(0.0, 200.0), pt(0.1, 200.0), pt(0.05, 200.0), None); + let (a, b) = (pt(0.0, 170.0), pt(0.1, 170.000_000_5)); + for short in [level(a, b), level(b, a)] { + let (at, _) = line_level(&[short], &d, pt(0.05, 168.0), 4.0).expect("on the level"); + assert!((at.y - 170.0).abs() < 1e-6, "{at:?}"); + } + } + + /// A level that would put the line past the largest distance a dimension allows is passed + /// over: the preview goes where the pointer is, with no level guide, or onto a level further + /// off within reach that keeps the line within the limit. + #[test] + fn a_level_past_the_distance_limit_is_passed_over() { + use vectorcraft_doc::{Node, NodeKind}; + let pt = Point::new; + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let add_level = |d: &mut vectorcraft_doc::Document, y: f64| { + let id = d.alloc_id(); + let mut drawn = Node::new(id, NodeKind::Group { children: vec![], clip: false }); + drawn.extras_mut().dimension = + Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, y), pt(380.0, y), pt(340.0, y), None))); + d.insert(Some(l), usize::MAX, drawn).unwrap(); + }; + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + // The points are at y = 400, so a line at y = 1,000,401 is 1,000,001 pt from them. + add_level(&mut d, 1_000_401.0); + for (also, offset) in [(None, 999_999.0), (Some(1_000_396.0), 999_996.0)] { + if let Some(y) = also { + add_level(&mut d, y); + } + let c = cx(&d, &s, &p); + let mut t = DimensionTool::default(); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&c, &ev(PointerKind::Down, x, y)); + t.pointer(&c, &ev(PointerKind::Up, x, y)); + } + let acts = t.pointer(&c, &ev(PointerKind::Move, 420.0, 1_000_399.0)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + assert_eq!(params["offset"], json!(offset)); + assert_eq!(t.level_guide.is_some(), also.is_some()); + } + } + /// The lines of the dimensions in the document are read only for a linear dimension. They are /// read with Smart Guides off too, so a line placed after Smart Guides are turned on lines up. #[test] diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c889671a6e..c4481d6034 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1735,10 +1735,12 @@ impl DirectSelectionTool { } self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides); self.moved = Some(d); - out.push(Action::Preview( - "object.transform".into(), - json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(d)), "copy": ev.mods.alt}), - )); + let mut params = json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(d)), "copy": ev.mods.alt}); + // An Alt-drag copy follows Draw Behind. + if ev.mods.alt { + params["drawBehind"] = json!(true); + } + out.push(Action::Preview("object.transform".into(), params)); out } fn release_move(&mut self, cx: &ToolContext, began: bool) -> Vec { diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 4f3b795921..87dc281405 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1990,8 +1990,7 @@ fn alt_dragged_copies_snap_by_the_anchor_pressed() { whole.set([b]); let c = cx(&d, &whole, &p); let mut t = DirectSelectionTool::new(false); - let copy = - |dx: f64, dy: f64| json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(dx, dy))), "copy": true}); + let copy = |dx: f64, dy: f64| json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(dx, dy))), "copy": true, "drawBehind": true}); // B's top-left corner, pressed 1 pt off, onto A's bottom-right one. let (v, labels) = drag(&mut t, &c, (301.0, 301.0), (203.0, 199.0), alt); assert_eq!((v, labels), (copy(-100.0, -100.0), vec!["anchor".to_string()])); @@ -2016,11 +2015,13 @@ fn alt_during_a_drag_by_an_anchor_toggles_the_copy() { whole.set([b]); let c = cx(&d, &whole, &p); let mut t = DirectSelectionTool::new(false); + // A copy follows Draw Behind (`drawBehind`); a move sends no such key. let preview = |dx: f64, dy: f64, copy: bool| { - Action::Preview( - "object.transform".into(), - json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(dx, dy))), "copy": copy}), - ) + let mut params = json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(dx, dy))), "copy": copy}); + if copy { + params["drawBehind"] = json!(true); + } + Action::Preview("object.transform".into(), params) }; assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)).is_empty()); assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 250.0, 250.0)), vec![Action::Begin("Move".into()), preview(-50.0, -50.0, false)]); diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index b2050dbbdf..792dff3b26 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -494,6 +494,18 @@ impl Tool for WidthTool { // Points moved together stay selected. (true, _, Some((id, ts))) if d.mode == Mode::Move => Some((id, ts.into_iter().map(|t| (t + dt).clamp(0.0, 1.0)).collect())), (true, _, sel) => sel, + // An Alt-click without a drag copies nothing: like a plain click on one of + // several selected points, it lets a double-click edit them all. + (false, false, _) if d.mode == Mode::Copy && !ev.mods.shift => { + if let Some(sel) = self + .before_press + .clone() + .filter(|(owner, ts)| *owner == d.spot.owner && ts.len() > 1 && ts.iter().any(|t| (t - d.spot.t).abs() <= SAME_T)) + { + self.before_click = Some((sel, false)); + } + Some((d.spot.owner, vec![d.t])) + } (false, _, _) => Some((d.spot.owner, vec![d.t])), }; vec![Action::Commit] @@ -1107,6 +1119,21 @@ mod tests { assert!(v.get("indices").is_none()); assert_eq!(t.selected_indices(&c, id), vec![2]); } + // With Alt held, a double-click without a drag edits every selected point too. + let alt = Mods { alt: true, ..Default::default() }; + let mut t = WidthTool::default(); + click(&mut t, 150.0, none); + click(&mut t, 250.0, shift); + let v = double_click(&mut t, 250.0, alt); + assert_eq!((&v["indices"], v.get("index")), (&json!([1, 3]), None)); + assert_eq!(t.selected_indices(&c, id), vec![1, 3], "the selection is kept"); + // An Alt-drag still copies the one point under the pointer, and selects the copy alone. + t.pointer(&c, &ev(PointerKind::Down, 250.0, 200.0, alt)); + let acts = t.pointer(&c, &ev(PointerKind::Drag, 270.0, 200.0, alt)); + let (cmd, v) = preview(&acts); + assert_eq!((cmd, &v["index"]), ("stroke.widthPoint.copy", &json!(3))); + t.pointer(&c, &ev(PointerKind::Up, 270.0, 200.0, alt)); + assert_eq!(t.selected.as_ref().map(|(_, ts)| ts.len()), Some(1)); // A discontinuous point among them keeps both halves, and double-clicking it keeps the others. let (mut d2, _) = doc_line(); let points = vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)]; diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 3c663006e5..0c032e0684 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -50,6 +50,11 @@ pub const SMOOTH_MIN_TOLERANCE: f64 = SMOOTH_MIN_FIDELITY / 640.0; /// pixels) at the lowest zoom (3.13 %). pub const SMOOTH_MAX_TOLERANCE: f64 = 100.0 / 0.0313; +/// The range (points) of `path.smoothRegion`'s `radius`, `path.joinScrub`'s `tolerance` and +/// `path.eraseSegments`' `width`, which the tools send as screen pixels divided by the zoom. +/// VectorCraft's own range. +pub const REACH_RANGE: (f64, f64) = (0.001, 1000.0); + /// Whether segment `i` of `sp` is straight, so the Smooth tool leaves it as it is: its handles lie /// on the line through its ends, and the segment runs from one end to the other without turning back. pub fn segment_is_straight(sp: &SubPath, i: usize) -> bool { @@ -375,6 +380,7 @@ pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec { } }); rest.reverse(); + // The loop skips ids that are already listed. let mut seen: std::collections::HashSet = v.iter().copied().collect(); for id in rest { if seen.insert(id) { diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index a815c02d2a..bfd930f8b1 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -493,19 +493,16 @@ impl Tool for FamilyTool { "lengthX" => self.length_x = arc_length(v, self.length_x), "lengthY" => self.length_y = arc_length(v, self.length_y), "reference" => self.reference = v.as_u64().unwrap_or(self.reference as u64).min(8) as usize, - "baseAlong" => { - if let Some(s) = v.as_str() { - self.base_along = if s.eq_ignore_ascii_case("y") { "y" } else { "x" }; - } - } + "baseAlong" => self.base_along = base_axis(v).unwrap_or(self.base_along), "slope" => self.slope = v.as_f64().filter(|n| n.is_finite()).map_or(self.slope, |n| n.clamp(-100.0, 100.0)), "fillArc" => self.fill_arc = v.as_bool().unwrap_or(self.fill_arc), // Report and persist the decay that shapes::spiral can actually draw. "decay" => self.decay = v.as_f64().unwrap_or(self.decay).clamp(5.0, 99.99), - "segments" => self.segments = v.as_u64().unwrap_or(10).clamp(2, 1000) as u32, + // A count that is not a whole number (a string, a fraction, a negative) keeps the current count. + "segments" => self.segments = v.as_u64().map_or(self.segments, |n| n.clamp(2, 1000) as u32), "clockwise" => self.clockwise = v.as_bool().unwrap_or(self.clockwise), - "rows" | "concentric" => self.rows = v.as_u64().unwrap_or(5).min(999) as u32, - "columns" | "radial" => self.columns = v.as_u64().unwrap_or(5).min(999) as u32, + "rows" | "concentric" => self.rows = v.as_u64().map_or(self.rows, |n| n.min(999) as u32), + "columns" | "radial" => self.columns = v.as_u64().map_or(self.columns, |n| n.min(999) as u32), "rowSkew" | "concentricSkew" => self.skew[0] = grid_skew(v, self.skew[0]), "columnSkew" | "radialSkew" => self.skew[1] = grid_skew(v, self.skew[1]), "frame" => self.frame = v.as_bool().unwrap_or(self.frame), @@ -519,14 +516,15 @@ impl Tool for FamilyTool { // the match above ignores leaves the drag's starting value as it was. if let Some(b) = self.before_drag.as_mut() { let finite = v.as_f64().is_some_and(f64::is_finite); + let whole = v.as_u64().is_some(); match key { "slope" if finite => b.slope = self.slope, "closed" if v.is_boolean() => b.closed = self.closed, - "baseAlong" if v.is_string() => b.base_along = self.base_along, + "baseAlong" if base_axis(v).is_some() => b.base_along = self.base_along, "decay" if v.as_f64().is_some() => b.decay = self.decay, - "segments" => b.segments = self.segments, - "rows" | "concentric" => b.rows = self.rows, - "columns" | "radial" => b.columns = self.columns, + "segments" if whole => b.segments = self.segments, + "rows" | "concentric" if whole => b.rows = self.rows, + "columns" | "radial" if whole => b.columns = self.columns, "rowSkew" | "concentricSkew" if finite => b.skew[0] = self.skew[0], "columnSkew" | "radialSkew" if finite => b.skew[1] = self.skew[1], _ => {} @@ -555,6 +553,15 @@ impl Tool for FamilyTool { } } +/// An arc's base axis from option value `v`: `"x"` or `"y"` in either case, else `None`. +fn base_axis(v: &Value) -> Option<&'static str> { + match v.as_str()? { + s if s.eq_ignore_ascii_case("x") => Some("x"), + s if s.eq_ignore_ascii_case("y") => Some("y"), + _ => None, + } +} + /// Arc segment length from a dialog or preference value, from 1e-9 to 1e6 pt (as the option check /// takes it). fn arc_length(v: &Value, current: f64) -> f64 { @@ -1003,6 +1010,83 @@ mod tests { assert_eq!((o["slope"].clone(), o["closed"].clone(), o["baseAlong"].clone()), (json!(-20.0), json!(false), json!("x"))); } + /// Values that are not whole numbers, as a damaged preferences file can hold them. + fn not_whole_numbers() -> [Value; 9] { + [json!("12"), json!("NaN"), json!(null), json!(true), json!(-3), json!(2.5), json!(1e300), json!({}), json!([7])] + } + + /// A spiral's segments and a grid's dividers keep their current count for a value that is not a + /// whole number; a whole number still sets the count within its range. + #[test] + fn family_tools_keep_their_counts_for_a_value_that_is_not_a_whole_number() { + for (id, key, set, high) in [ + ("spiral", "segments", 23, 1000), + ("rectangularGrid", "rows", 7, 999), + ("rectangularGrid", "columns", 8, 999), + ("polarGrid", "concentric", 7, 999), + ("polarGrid", "radial", 8, 999), + ] { + let mut t = FamilyTool::new(id); + t.set_option(key, &json!(set)); + let before = t.options(); + for v in not_whole_numbers() { + t.set_option(key, &v); + assert_eq!(t.options(), before, "{id} {key} {v}"); + } + t.set_option(key, &json!(u64::MAX)); + assert_eq!(t.options()[key], json!(high), "{id} {key}"); + } + let mut t = FamilyTool::new("spiral"); + t.set_option("segments", &json!(1)); + assert_eq!(t.options()["segments"], json!(2)); + } + + /// The Arc tool keeps its base axis for a value other than x or y. + #[test] + fn arc_keeps_its_base_axis_for_a_value_other_than_x_or_y() { + let mut t = FamilyTool::new("arc"); + t.set_option("baseAlong", &json!("Y")); + for v in [json!("z"), json!(""), json!("xy"), json!(null), json!(1)] { + t.set_option("baseAlong", &v); + assert_eq!(t.options()["baseAlong"], json!("y"), "{v}"); + } + t.set_option("baseAlong", &json!("X")); + assert_eq!(t.options()["baseAlong"], json!("x")); + } + + /// A count or base axis the option ignores while a shape is dragged out leaves the drag's + /// starting value for Escape. + #[test] + fn escape_puts_back_the_drag_start_counts_after_an_ignored_value() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + for (id, keys) in [ + ("spiral", vec!["segments"]), + ("rectangularGrid", vec!["rows", "columns"]), + ("polarGrid", vec!["concentric", "radial"]), + ("arc", vec!["baseAlong"]), + ] { + let mut t = FamilyTool::new(id); + let start = t.options(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)); + for k in [ToolKey::Up, ToolKey::Right, ToolKey::Letter('f')] { + t.key(&cx, k, Mods::default()); + } + assert_ne!(t.options(), start, "{id}"); + for k in &keys { + for v in not_whole_numbers().into_iter().chain([json!("z")]) { + t.set_option(k, &v); + } + } + t.key(&cx, ToolKey::Escape, Mods::default()); + assert_eq!(t.options(), start, "{id}"); + } + } + /// Alt adjusts the segment count in whole winds while keeping it within 2 to 1000. #[test] fn spiral_drag_alt_keeps_the_segments_within_2_to_1000() { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index dc123e6cc1..a34c819761 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -96,6 +96,20 @@ fn fit_tolerance(cx: &ToolContext, px: f64) -> f64 { cx.tol(px).clamp(super::MIN_FIT_TOLERANCE, super::MAX_FIT_TOLERANCE) } +/// The `fidelity` (points) the Smooth tool, and an Alt smoothing drag, send `path.smoothRegion` for +/// `px` screen pixels at the current zoom, within the range the command takes +/// ([`super::SMOOTH_MIN_TOLERANCE`]..[`super::SMOOTH_MAX_TOLERANCE`]). +fn smooth_tolerance(cx: &ToolContext, px: f64) -> f64 { + cx.tol(px).clamp(super::SMOOTH_MIN_TOLERANCE, super::SMOOTH_MAX_TOLERANCE) +} + +/// The distance (points) the Smooth, Join and Path Eraser tools send for `px` screen pixels at the +/// current zoom, within [`super::REACH_RANGE`]. +fn reach(cx: &ToolContext, px: f64) -> f64 { + let (lo, hi) = super::REACH_RANGE; + cx.tol(px).clamp(lo, hi) +} + pub struct GestureTool { /// How many points the last preview of the stroke had ([`crate::previews_at`]); 0 when it was /// fitted coarser than the stroke kept ([`PREVIEW_FIDELITY_PX`]). @@ -1550,13 +1564,13 @@ impl GestureTool { fn finish(&mut self, cx: &ToolContext, m: Mods) -> Vec { let pts = &self.points; let has_sel = !cx.selection.is_empty(); - let tol = cx.tol(self.edit_within); - let radius = cx.tol(SMOOTH_RADIUS); + let tol = reach(cx, self.edit_within); + let radius = reach(cx, SMOOTH_RADIUS); if self.smoothing { if pts.len() >= 2 && has_selected_smooth_path(cx) { return vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.smooth_fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.smooth_fidelity)}), )]; } return vec![]; @@ -1621,10 +1635,10 @@ impl GestureTool { "smooth" if pts.len() >= 2 && has_selected_smooth_path(cx) => { vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.fidelity)}), )] } - "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": cx.tol(8.0)}))], + "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": reach(cx, 8.0)}))], "join" if pts.len() >= 2 => vec![Action::Exec("path.joinScrub".into(), json!({"points": points_json(pts), "tolerance": tol}))], _ => vec![], } @@ -1906,7 +1920,7 @@ impl Tool for GestureTool { // release smooths. if (self.id == "smooth" || self.smoothing) && has_selected_smooth_path(cx) - && let Some(path) = self.smooth_band(cx.tol(SMOOTH_RADIUS)) + && let Some(path) = self.smooth_band(reach(cx, SMOOTH_RADIUS)) { o.push(Overlay::SharedPath { path, color: FEEDBACK, width: 1.0, dash: Some(0.0) }); } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 1ffcf1c37b..00f0ebc93e 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -309,6 +309,45 @@ fn fidelity_sent_stays_within_what_path_freehand_takes() { } } +/// `path.smoothRegion`, `path.joinScrub` and `path.eraseSegments` refuse a radius, Fidelity, +/// tolerance or width outside their ranges, so at a zoom beyond the view's range the Smooth, Join +/// and Path Eraser tools, and an Alt smoothing drag, send the nearer end of each. +#[test] +fn smooth_join_and_path_eraser_send_values_their_commands_take() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let (reach_lo, reach_hi) = crate::draw2::REACH_RANGE; + let (tol_lo, tol_hi) = (crate::draw2::SMOOTH_MIN_TOLERANCE, crate::draw2::SMOOTH_MAX_TOLERANCE); + let alt = Mods { alt: true, ..Default::default() }; + for (zoom, fidelity, reach, tol) in [(0.001, 100.0, reach_hi, tol_hi), (100_000.0, 0.05, reach_lo, tol_lo)] { + cx.zoom = zoom; + // The same drag on screen at each zoom. + let pts: Vec<_> = [(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)].iter().map(|&(x, y)| (x / zoom, y / zoom)).collect(); + let sent = |acts: &[Vec]| match acts.last().and_then(|a| a.first()) { + Some(Action::Exec(c, v)) => (c.clone(), v.clone()), + a => panic!("expected a command at {zoom}x, got: {a:?} in {acts:?}"), + }; + let mut smooth = GestureTool::new("smooth"); + smooth.set_option("fidelity", &json!(fidelity)); + let mut pencil = GestureTool::new("pencil"); + pencil.set_option("altSmooth", &json!(true)); + pencil.set_option("smoothFidelity", &json!(fidelity)); + for (what, acts) in [("smooth", drag(&mut smooth, &cx, &pts, Mods::default())), ("pencil", drag_held(&mut pencil, &cx, &pts, alt))] { + let (c, v) = sent(&acts); + assert_eq!(c, "path.smoothRegion", "{what} at {zoom}x"); + assert_eq!((v["radius"].as_f64(), v["fidelity"].as_f64()), (Some(reach), Some(tol)), "{what} at {zoom}x: {v}"); + } + let (c, v) = sent(&drag(&mut GestureTool::new("join"), &cx, &pts, Mods::default())); + assert_eq!((c.as_str(), v["tolerance"].as_f64()), ("path.joinScrub", Some(reach)), "join at {zoom}x: {v}"); + let (c, v) = sent(&drag(&mut GestureTool::new("pathEraser"), &cx, &pts, Mods::default())); + assert_eq!((c.as_str(), v["width"].as_f64()), ("path.eraseSegments", Some(reach)), "path eraser at {zoom}x: {v}"); + } +} + /// The Blob Brush's Fidelity stays in points (#5729 is the Pencil's and the Paintbrush's): its /// stroke, and another tool chosen while it is drawn, send it as set at any zoom. #[test] @@ -1602,6 +1641,38 @@ fn smoothing_band_shows_no_seam_where_it_turns_across_a_square_side() { } } +/// Zoomed out far enough that the Smooth tool's radius in points passes the top of +/// [`crate::draw2::REACH_RANGE`], the band a smoothing drag shows has the radius its release sends. +#[test] +fn smoothing_band_at_the_lowest_zoom_has_the_radius_the_release_sends() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.zoom = 0.005; + let r = crate::draw2::REACH_RANGE.1; + assert!(cx.tol(SMOOTH_RADIUS) > r, "the radius on screen is past the range at {}x", cx.zoom); + let ends = [Point::new(1000.0, 1000.0), Point::new(5000.0, 1000.0)]; + let mut t = GestureTool::new("smooth"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, ends[0].x, ends[0].y)); + for i in 1..=20 { + let q = ends[0].lerp(ends[1], f64::from(i) / 20.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, q.x, q.y)); + } + let mut frames = 0; + while t.overlays_pending() { + assert!(frames < 10_000, "the band reaches the whole drag"); + bands(&t, &cx); + frames += 1; + } + check_band(&t, &cx, r); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, ends[1].x, ends[1].y)); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("expected a command, got {acts:?}") }; + assert_eq!((c.as_str(), v["radius"].as_f64()), ("path.smoothRegion", Some(r)), "{v}"); +} + /// One straight piece of a square's outline along a side, where the band goes on across only part /// of it, shows only the part with nothing across. #[test] diff --git a/crates/tools/src/guides.rs b/crates/tools/src/guides.rs index e9f7bf7318..ccbf258512 100644 --- a/crates/tools/src/guides.rs +++ b/crates/tools/src/guides.rs @@ -25,10 +25,10 @@ mod snap; mod targets; pub(crate) use bitangent::TangentLine; -pub(crate) use snap::hold_on_path; pub use snap::{ DEFAULT_CONSTRUCTION_ANGLES, DrawSnap, HandleSnap, Leave, PointSnap, construction_angles, distance_guides, snap_draw, snap_pick, square, }; +pub(crate) use snap::{SnapSettings, hold_on_path}; use targets::Kind; pub use targets::Targets; #[cfg(test)] diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index de09341bc7..0a48b35001 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -376,6 +376,28 @@ impl SnapKey { } } +/// Every setting that can move a snapped drawn point besides the document: the window and the +/// zoom, the options and tolerances [`SnapKey`] holds except the guides' color and labels, and +/// the construction guides' angles a [`Leave::segment`] follows. A tool that keeps a hover's +/// snapped point compares two of these to see whether a click would still snap the same way. +#[derive(PartialEq)] +pub(crate) struct SnapSettings { + screen: Option, + zoom: f64, + view: [bool; 7], + snap_to_glyph: Option, + alignment_lines: bool, + tolerances: [f64; 2], + angles: &'static [f64], +} + +impl SnapSettings { + pub(crate) fn of(cx: &ToolContext) -> Self { + let SnapKey { screen, view, snap_to_glyph, style, tolerances, .. } = SnapKey::of(cx, &[]); + Self { screen, zoom: cx.zoom, view, snap_to_glyph, alignment_lines: style.lines, tolerances, angles: cx.construction_angles } + } +} + /// The part of the document the window shows (none headless: all of it). pub(super) fn visible(cx: &ToolContext) -> Option { let s = cx.screen?; @@ -493,6 +515,14 @@ impl DrawSnap { t.nearest_point(p, tol).is_some_and(|(a, _)| at(a)) || t.crossing(p, tol).is_some_and(at) } + /// Whether a point at `p` leaving `from` lands on one of the targets the last hover or press + /// gathered ([`Targets::snap_hit`]), whether or not its guides show. False with Smart Guides + /// off, with no targets, and while pixels or the grid snap instead. + pub(crate) fn lands_on_target(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> bool { + let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return false }; + cx.smart_guides && !cx.snaps_to_pixel(*op) && !cx.snap_to_grid && t.snap_hit(p, from, cx.tol(*tol)).2 + } + /// The guides of the last snap. pub fn guides(&self) -> &[Overlay] { &self.guides diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 94344aab2c..5f30ce3a7c 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -778,27 +778,35 @@ impl Targets { /// that way into line with the nearest target; else, before lining up, it lands on a /// construction guide through it, where a target's line crosses the guide if one does nearby. pub fn snap_from(&self, p: Point, from: Option<&Leave>, tol: f64) -> (Point, Vec) { + let (q, guides, _) = self.snap_hit(p, from, tol); + (q, guides) + } + + /// [`Self::snap_from`], and whether `p` landed on a target (an anchor or center, a crossing, + /// a segment, a construction guide or a target's line), whether or not its guides show. A + /// point Shift kept to its angle without lining up with a target landed on none. + pub(crate) fn snap_hit(&self, p: Point, from: Option<&Leave>, tol: f64) -> (Point, Vec, bool) { if let Some(f) = from && let Some(q) = f.constrained(p) { return match self.slide(f.at, q - f.at, q, tol, true) { - Some((q, target)) => (q, self.lined_up(q, target)), - None => (q, vec![]), + Some((q, target)) => (q, self.lined_up(q, target), true), + None => (q, vec![], false), }; } if let Some((q, k)) = self.nearest_point(p, tol) { - return (q, self.label(q, k.label()).into_iter().collect()); + return (q, self.label(q, k.label()).into_iter().collect(), true); } if let Some(q) = self.crossing(p, tol) { - return (q, self.label(q, "intersect").into_iter().collect()); + return (q, self.label(q, "intersect").into_iter().collect(), true); } if let Some(f) = from.filter(|f| f.contact) && let Some((q, perpendicular, dir)) = self.touching(f.at, p, tol) { - return (q, self.touch_guides(f.at, q, perpendicular, dir, tol)); + return (q, self.touch_guides(f.at, q, perpendicular, dir, tol), true); } if let Some(q) = self.on_segment(p, tol) { - return (q, self.label(q, Kind::Edge.label()).into_iter().collect()); + return (q, self.label(q, Kind::Edge.label()).into_iter().collect(), true); } // A construction guide through the point it leaves, else a dragged segment's extension: // it lands on the guide, sliding into line with a target crossing it nearby. @@ -809,8 +817,8 @@ impl Targets { { let construction = |q: Point| Overlay::Line { a: at, b: q, color: self.style.color, dashed: false }; return match self.slide(at, dir, q, tol, false) { - Some((q, target)) => (q, std::iter::once(construction(q)).chain(self.lined_up(q, target)).collect()), - None => (q, vec![construction(q)]), + Some((q, target)) => (q, std::iter::once(construction(q)).chain(self.lined_up(q, target)).collect(), true), + None => (q, vec![construction(q)], true), }; } let mut out = p; @@ -840,7 +848,7 @@ impl Targets { if aligned { ov.extend(self.label(out, "align")); } - (out, ov) + (out, ov, aligned) } /// Where a line from `at` through a point near `p` touches a target segment: square to it diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 6368ba160b..7acef24638 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -12,18 +12,31 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! +//! While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a +//! protractor around the arc's center: a tick across its circle every 15° from where the arc +//! starts, a longer one every 90°, and one where it ends. The piece the next click adds shows its +//! protractor only while the Pen tool's rubber band preference shows that piece. With Smart Guides +//! on, the end of a continuous arc goes onto the nearest tick of that protractor when the tick lies +//! within the snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither +//! the grid nor pixels snap drawn points. A sharp-corner arc, and a continuous arc that has no +//! direction to follow, sweep the arc size, so their ends are not snapped to a tick. After a snap +//! setting changes under a still pointer, the hover's preview, protractor, distance label and +//! Smart Guides are hidden until the pointer moves; when the view, the document or the selection +//! changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, +//! so it does not change the snapping. use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; -use crate::guides::{DrawSnap, Leave}; +use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The tool's id. pub const ID: &str = "quickPen"; @@ -36,6 +49,10 @@ pub const TURN_STEP: f64 = 15.0; /// The smallest and largest arc size (degrees). pub const MIN_TURN: f64 = 1.0; pub const MAX_TURN: f64 = 359.0; +/// Degrees between the protractor's ticks, and the steps a continuous arc's sweep snaps to. +pub const TICK_STEP: f64 = 15.0; +/// Half the length (screen points) of a protractor tick; the ticks every 90° are twice as long. +const TICK_PX: f64 = 4.0; /// Screen points the pointer moves after a press before the press drags. const DRAG_PX: f64 = 3.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight @@ -190,6 +207,82 @@ pub fn append(sp: &mut SubPath, piece: &Piece) -> bool { true } +/// The circle an arc piece lies on: its center and radius, the point the arc starts from, and the +/// arc's signed sweep (radians; positive bulges to the left of the direction drawn). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ArcCircle { + pub center: Point, + pub radius: f64, + pub start: Point, + pub sweep: f64, +} + +/// The circle of the arc `piece` adds at the end of `sp`, as [`append`] draws it. None for a line, +/// a piece that ends where `sp` does, and a circle whose center or radius is past the document's +/// coordinate limit. +pub fn arc_circle(sp: &SubPath, piece: &Piece) -> Option { + let a = sp.anchors.last()?.p; + let c = piece.to - a; + let l = c.hypot(); + if l <= 1e-9 || !l.is_finite() { + return None; + } + let s = turn_of(sp, piece, a, piece.to)?; + let half = s.abs() / 2.0; + let radius = l / (2.0 * half.sin()); + // The center lies on the chord's perpendicular bisector, on the side away from the bulge for + // less than a half circle and on the bulge's side for more. + let center = a + c / 2.0 + rot(c / l, FRAC_PI_2) * (radius * half.cos() * s.signum()); + (radius <= MAX_COORD && center.x.abs() <= MAX_COORD && center.y.abs() <= MAX_COORD).then_some(ArcCircle { center, radius, start: a, sweep: s }) +} + +/// The protractor tick nearest the end of a continuous arc ending at `piece.to`: the point on the +/// arc's circle ([`arc_circle`]) where the sweep is a whole number of [`TICK_STEP`]s. None for +/// other pieces, a continuous arc with no direction to follow (it sweeps the arc size, as a +/// sharp-corner arc does), an arc without a circle, a sweep that rounds to nothing or to a whole +/// circle, and a tick past the document's coordinate limit. +pub fn tick_end(sp: &SubPath, piece: &Piece) -> Option { + if piece.stroke != Stroke::ContinuousArc { + return None; + } + arrival(sp)?; + let arc = arc_circle(sp, piece)?; + let step = TICK_STEP.to_radians(); + let s = (arc.sweep / step).round() * step; + (s.abs() > step / 2.0 && s.abs() < 2.0 * PI - step / 2.0) + .then(|| arc.center + rot(arc.start - arc.center, s)) + .filter(|b| b.x.abs() <= MAX_COORD && b.y.abs() <= MAX_COORD) +} + +/// The protractor around `arc`'s center: a tick across its circle every [`TICK_STEP`] from where +/// the arc starts, twice as long every 90°, and one where the arc ends. +fn protractor(cx: &ToolContext, arc: &ArcCircle) -> BezPath { + let step = TICK_STEP.to_radians(); + let out = (arc.start - arc.center) / arc.radius; + let ticks = (arc.sweep.abs() / step + 1e-9).floor() as usize; + let mut bp = BezPath::new(); + let mut tick = |angle: f64, long: bool| { + let d = rot(out, angle); + let half = cx.tol(if long { 2.0 * TICK_PX } else { TICK_PX }); + bp.move_to(arc.center + d * (arc.radius - half)); + bp.line_to(arc.center + d * (arc.radius + half)); + }; + let per_right_angle = (90.0 / TICK_STEP).round() as usize; + for k in 0..=ticks { + tick(arc.sweep.signum() * k as f64 * step, k % per_right_angle == 0); + } + if arc.sweep.abs() - ticks as f64 * step > 1e-6 { + tick(arc.sweep, false); + } + bp +} + +/// The last two of the first `kept` points of `sp`: where the piece after them starts, and the +/// direction it arrives in. +fn tail(sp: &SubPath, kept: usize) -> Option { + Some(SubPath::new(sp.anchors.get_range(kept.saturating_sub(2)..kept)?, false)) +} + /// Closes `sp`: a last point that lies on the first joins it (the first point takes its incoming /// handle); otherwise a straight segment closes the path. Fewer than two points stay open. pub fn close(sp: &mut SubPath) { @@ -269,12 +362,14 @@ impl Drawing { } /// The press in progress: where it went down, whether it has dragged, and whether it began an undo -/// step (a piece it adds). +/// step (a piece it adds). `end` is the pointer for the end of the piece it adds and where the +/// snap put that end, before the protractor's tick. #[derive(Clone, Copy, Debug, PartialEq)] struct Press { at: Point, dragged: bool, begun: bool, + end: Option<(Point, Point)>, } pub struct QuickPenTool { @@ -284,11 +379,16 @@ pub struct QuickPenTool { press: Option, hover: Option, snap: DrawSnap, + /// The pointer while it hovers, whether it lies on a Smart Guide target ([`Self::landed`]), and + /// the snap settings then; `hover` is where Smart Guides put it. The protractor's tick is + /// applied when the point is used ([`Self::hover_end`]), for the action chosen then. A press + /// clears it. + pointer: Option<(Point, bool, SnapSettings)>, } impl Default for QuickPenTool { fn default() -> Self { - Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default() } + Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default(), pointer: None } } } @@ -375,11 +475,16 @@ impl QuickPenTool { return vec![]; } // The snapping leaves from the point before the piece being dragged, as the press found it. - let from = self.drawing.as_ref().and_then(|dr| { - let sp = dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?; - sp.anchors.get(dr.kept.last()?.checked_sub(1)?).map(|a| Leave::segment(cx, a.p, false).without_contact()) - }); + let before = self.before_piece(); + let from = before.as_ref().and_then(|sp| sp.anchors.last()).map(|a| Leave::segment(cx, a.p, false).without_contact()); let q = self.snap.drag(cx, p, from.as_ref()); + if let Some(pr) = self.press.as_mut() { + pr.end = Some((p, q)); + } + let q = match self.drawing.as_ref().and_then(|dr| dr.pieces.last()) { + Some(piece) => self.press_end(cx, piece, p, q), + None => q, + }; let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] }; if last.to == q { return vec![]; @@ -388,6 +493,59 @@ impl QuickPenTool { vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] } + /// Where `piece`, which a press draws, ends with the pointer at `p` that the snap put at `q`: + /// on the protractor's tick when [`Self::on_tick`] puts it there for the piece's action. + fn press_end(&self, cx: &ToolContext, piece: &Piece, p: Point, q: Point) -> Point { + let Some(sp) = self.before_piece() else { return q }; + let from = sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact()); + let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); + self.on_tick(cx, &sp, *piece, p, q, landed) + } + + /// `q`, where the last snap put the end of `piece` drawn after `sp` (the pointer being at `p`), + /// moved onto the protractor's nearest tick ([`tick_end`]) when Smart Guides are on, the tick + /// lies within the snapping tolerance of the pointer, and nothing else snapped the point: the + /// snap left it where the pointer is, the pointer is on no Smart Guide target (shown or not, + /// `landed`), and neither the grid nor pixels snap drawn points. + fn on_tick(&self, cx: &ToolContext, sp: &SubPath, piece: Piece, p: Point, q: Point, landed: bool) -> Point { + if landed || !cx.smart_guides || q != p || cx.snap_to_grid || cx.snaps_to_pixel(PixelOp::Drawing) { + return q; + } + tick_end(sp, &Piece { to: q, ..piece }).filter(|b| b.distance(q) <= cx.tol(cx.snapping_tolerance)).unwrap_or(q) + } + + /// Whether the pointer at `p`, which the last snap left in place at `q`, lies on a Smart Guide + /// target leaving `from`, shown or not ([`DrawSnap::lands_on_target`]). A point the snap moved + /// is not asked about, since a tick applies only to a point left in place. + fn landed(&self, cx: &ToolContext, p: Point, q: Point, from: Option<&Leave>) -> bool { + q == p && self.snap.lands_on_target(cx, p, from) + } + + /// Where the next click's piece after `sp` ends while the pointer hovers: the hover's snapped + /// point, on the protractor's tick when [`Self::on_tick`] puts it there. None before the + /// pointer moves after a press, and while the hover is stale ([`Self::hover_stale`]). + fn hover_end(&self, cx: &ToolContext, sp: &SubPath) -> Option { + let (&(p, landed, _), q) = (self.pointer.as_ref()?, self.hover?); + if self.hover_stale(cx) { + return None; + } + Some(self.on_tick(cx, sp, self.piece_to(q), p, q, landed)) + } + + /// Whether the snap settings changed since the pointer last moved: the hover's snapped point + /// and its tick may then not be where a click puts the point, so the hover shows nothing until + /// the pointer moves again. + fn hover_stale(&self, cx: &ToolContext) -> bool { + self.pointer.as_ref().is_some_and(|(_, _, at)| *at != SnapSettings::of(cx)) + } + + /// During a press that adds a piece: the points before that piece, as the press found them + /// (the last two, see [`tail`]). + fn before_piece(&self) -> Option { + let dr = self.drawing.as_ref()?; + tail(dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?, *dr.kept.last()?) + } + /// Draws the path again after its last piece changed: a preview while a press draws that /// piece, else a step of its own. fn redraw(&self) -> Vec { @@ -433,13 +591,15 @@ impl QuickPenTool { return vec![]; } let from = self.leave(cx).map(|l| l.1); - let q = self.snap.press(cx, p, &[id], from.as_ref()); + let snapped = self.snap.press(cx, p, &[id], from.as_ref()); + let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, snapped, from.as_ref()); + let q = self.on_tick(cx, sp, self.piece_to(snapped), p, snapped, landed); let (piece, kept) = (self.piece_to(q), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { dr.push(piece, kept); dr.before_press = shared_node(cx.doc, id).cloned(); } - self.press = Some(Press { at: p, dragged: false, begun: true }); + self.press = Some(Press { at: p, dragged: false, begun: true, end: Some((p, snapped)) }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) @@ -459,6 +619,7 @@ impl QuickPenTool { /// Ends the path being drawn; a press that added a piece is taken back. fn end(&mut self) -> Vec { self.drawing = None; + self.pointer = None; self.snap.clear(); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], @@ -498,13 +659,23 @@ impl Tool for QuickPenTool { match ev.kind { PointerKind::Move => { let (on, from) = self.leave(cx).unzip(); - self.hover = Some(self.snap.hover(cx, p, on.as_slice(), from.as_ref())); + let q = self.snap.hover(cx, p, on.as_slice(), from.as_ref()); + self.hover = Some(q); + self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()), SnapSettings::of(cx))); vec![] } PointerKind::Down => { if self.press.is_some() { return vec![]; } + // The hover shows again when the pointer moves after the press: the point the press + // places can lie on a tick away from it. A stale hover's guides stay hidden, also + // when the press snaps nothing. + if self.hover_stale(cx) { + self.snap.clear(); + } + self.hover = None; + self.pointer = None; self.press_down(cx, p) } PointerKind::Drag => { @@ -638,11 +809,17 @@ impl Tool for QuickPenTool { } ToolKey::AltTap => { self.action = self.action.next(); - // A drag under way draws its piece with the new action. + // A drag under way draws its piece with the new action. Its end goes through the + // protractor's tick again for that action: a continuous arc's end on a tick goes + // back to where the snap put the pointer for another action, and the other way. if self.press.is_some_and(|pr| pr.begun) && self.held(cx) { - let (action, turn) = (self.action, self.turn); - if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { - (last.stroke, last.turn, last.flip) = (action, turn, false); + let (action, turn, end) = (self.action, self.turn, self.press.and_then(|pr| pr.end)); + let piece = self.drawing.as_ref().and_then(|dr| dr.pieces.last()).map(|&pc| { + let pc = Piece { stroke: action, turn, flip: false, ..pc }; + end.map_or(pc, |(p, q)| Piece { to: self.press_end(cx, &pc, p, q), ..pc }) + }); + if let (Some(piece), Some(last)) = (piece, self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut())) { + *last = piece; } return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } @@ -670,13 +847,34 @@ impl Tool for QuickPenTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.pointer = None; + } + + /// A hover's snapped point and its tick depend on the art and the view under a still pointer. + fn wants_rehover(&self) -> bool { + self.pointer.is_some() } fn overlays(&self, cx: &ToolContext) -> Vec { - let mut o = self.snap.guides().to_vec(); + // A stale hover's Smart Guides go with its preview. + let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; let Some((id, sp)) = self.active(cx) else { return o }; + let end = if self.press.is_none() { self.hover_end(cx, sp) } else { None }; + // The arc being drawn: the piece a press drags, or the piece the next click adds while the + // rubber band shows it. + let arc = match self.press { + Some(pr) if pr.begun => { + self.before_piece().zip(self.drawing.as_ref().and_then(|dr| dr.pieces.last())).and_then(|(sp, piece)| arc_circle(&sp, piece)) + } + Some(_) => None, + None => end.filter(|_| cx.pen_rubber_band).and_then(|h| arc_circle(sp, &self.piece_to(h))), + }; + if let Some(arc) = arc { + o.push(Overlay::Path { path: protractor(cx, &arc), color: FEEDBACK, width: 1.0, dashed: false }); + } if self.press.is_none() - && let Some(h) = self.hover + && !self.hover_stale(cx) + && let Some(h) = end.or(self.hover) { if cx.pen_rubber_band && let Some(path) = self.rubber_band(sp, h) diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index f5ab9986d1..1319948423 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::testutil::*; use vectorcraft_doc::Selection; -use vectorcraft_geom::{ParamCurve, PathData}; +use vectorcraft_geom::{ParamCurve, PathData, PathSeg}; fn pt(x: f64, y: f64) -> Point { Point::new(x, y) @@ -196,6 +196,109 @@ fn the_first_click_starts_a_path() { assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); } +/// The circle `arc_circle` gives is the one `append` draws the arc on, for sharp-corner arcs of +/// less and more than a half circle, flipped, and continuous arcs; a line has none. +#[test] +fn the_arc_circle_is_the_circle_the_arc_is_drawn_on() { + let line = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line)], false); + let cases = [ + (start(pt(0.0, 0.0)), Piece { turn: 90.0, ..piece(100.0, 0.0, Stroke::SharpArc) }), + (start(pt(0.0, 0.0)), Piece { turn: 270.0, flip: true, ..piece(100.0, 30.0, Stroke::SharpArc) }), + (line.clone(), piece(200.0, 100.0, Stroke::ContinuousArc)), + (line.clone(), piece(40.0, 60.0, Stroke::ContinuousArc)), + ]; + for (sp, pc) in cases { + let arc = arc_circle(&sp, &pc).unwrap(); + let from = sp.anchors.len() - 1; + let mut drawn = sp.clone(); + append(&mut drawn, &pc); + assert!(on_circle(&drawn, from, arc.center, arc.radius), "{pc:?} {arc:?}"); + assert_eq!(arc.start, sp.anchors.last().unwrap().p); + } + assert!(arc_circle(&line, &piece(200.0, 100.0, Stroke::Line)).is_none()); +} + +/// A continuous arc's end goes to the protractor tick nearest it: on the same circle, where the +/// sweep is a whole number of 15° steps, so an end that sweeps 61° goes to the drawn 60° tick. A +/// sharp-corner arc and a sweep that rounds to a whole circle have no tick to go to. +#[test] +fn a_continuous_arc_end_goes_to_the_nearest_tick() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line)], false); + let half = 30.5f64.to_radians(); + let to = pt(100.0 + 80.0 * half.cos(), 80.0 * half.sin()); + let pc = Piece { to, ..piece(0.0, 0.0, Stroke::ContinuousArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + assert!((arc.sweep.to_degrees() - 61.0).abs() < 1e-9, "{arc:?}"); + let b = tick_end(&sp, &pc).unwrap(); + let after = arc_circle(&sp, &Piece { to: b, ..pc }).unwrap(); + assert!((after.sweep.to_degrees() - 60.0).abs() < 1e-9, "{after:?}"); + assert!(after.center.distance(arc.center) < 1e-9 && (after.radius - arc.radius).abs() < 1e-9, "the same circle"); + let ticks = protractor(&cx, &arc); + let on_a_tick = ticks.segments().any(|seg| (seg.eval(1.0) - seg.eval(0.0)).cross(b - seg.eval(0.0)).abs() < 1e-6); + assert!(on_a_tick, "{b:?} lies across a drawn tick"); + assert!(tick_end(&sp, &Piece { stroke: Stroke::SharpArc, ..pc }).is_none()); + // Nearly straight behind: the sweep rounds to 360°. + assert!(tick_end(&sp, &Piece { to: pt(20.0, 0.5), ..pc }).is_none()); +} + +/// An end inside the document's coordinate limit whose tick lies past it has no tick to go to: a +/// 59° sweep whose 60° tick is 0.4 pt past the limit. +#[test] +fn a_tick_past_the_coordinate_limit_is_not_used() { + let x = vectorcraft_doc::MAX_COORD - 87.5; + let sp = build(&start(pt(x - 100.0, 0.0)), &[piece(x, 0.0, Stroke::Line)], false); + let half = 29.5f64.to_radians(); + let pc = Piece { to: pt(x + 100.0 * half.cos(), 100.0 * half.sin()), ..piece(0.0, 0.0, Stroke::ContinuousArc) }; + assert!(pc.to.x < vectorcraft_doc::MAX_COORD); + assert!(tick_end(&sp, &pc).is_none()); + let inside = Piece { to: pt(pc.to.x - 10.0, pc.to.y), ..pc }; + assert!(tick_end(&sp, &inside).is_some(), "a tick inside the limit is used"); +} + +/// A continuous arc that starts a path has no direction to follow and sweeps the arc size, so its +/// end has no tick to go to: with a 100° arc size, a tick at 105° would move the end off the arc +/// the click draws. +#[test] +fn a_continuous_arc_without_a_direction_has_no_tick() { + let sp = start(pt(0.0, 0.0)); + let pc = Piece { turn: 100.0, ..piece(100.0, 10.0, Stroke::ContinuousArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + assert!((arc.sweep.to_degrees() - 100.0).abs() < 1e-9, "{arc:?}"); + assert!(tick_end(&sp, &pc).is_none()); + // After a line, the same end has a tick. + let sp = build(&start(pt(-100.0, 0.0)), &[piece(0.0, 0.0, Stroke::Line)], false); + assert!(tick_end(&sp, &pc).is_some()); +} + +/// The protractor has a tick every 15° of the sweep, each across the arc's circle, the first +/// through the arc's start; a sweep that is not a whole number of steps adds a tick at its end. +#[test] +fn the_protractor_ticks_lie_across_the_arc() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let sp = start(pt(0.0, 0.0)); + for (turn, ticks) in [(90.0, 7), (100.0, 8)] { + let pc = Piece { turn, ..piece(100.0, 0.0, Stroke::SharpArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + let segs: Vec<_> = protractor(&cx, &arc).segments().collect(); + assert_eq!(segs.len(), ticks, "{turn}"); + for seg in &segs { + let (a, b) = (seg.eval(0.0), seg.eval(1.0)); + assert!((a.midpoint(b).distance(arc.center) - arc.radius).abs() < 1e-9); + assert!((b - a).cross(arc.center - a).abs() < 1e-6, "points at the center"); + } + let through = |seg: &PathSeg, q: Point| (seg.eval(1.0) - seg.eval(0.0)).cross(q - seg.eval(0.0)).abs() < 1e-6; + assert!(through(segs.first().unwrap(), arc.start)); + assert!(through(segs.last().unwrap(), pc.to)); + } +} + /// The rubber band previews exactly the piece a click adds. #[test] fn the_rubber_band_is_the_next_piece() { diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index eee6600591..22c98e62db 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -2020,6 +2020,10 @@ impl SelectionTool { self.state = State::Moving { start, press, hold, grip, began: true, deselect: None, key: None, exclude: None }; self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y))); let mut params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt }); + // An Alt-drag copy follows Draw Behind. + if m.alt { + params["drawBehind"] = json!(true); + } if backquote { params["objects"] = json!(false); params["patterns"] = json!(true); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 2cf9891693..ff95ef68ce 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -3143,3 +3143,40 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() { let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0)); assert!(!is_select(&down), "every anchor: {down:?}"); } + +/// A press near an anchor of a member selected inside a group grabs the member by that anchor, +/// so with Smart Guides or Snap to Point on that anchor is the point that snaps during the move. +#[test] +fn a_press_near_an_anchor_of_a_selected_group_member_grabs_it_by_that_anchor() { + use vectorcraft_doc::{Appearance, Document, Node}; + use vectorcraft_geom::shapes; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (outer, inner, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = |id: NodeId, x: f64| Node::path(id, shapes::rectangle(Rect::new(x, 100.0, x + 50.0, 150.0)), Appearance::default_art()); + d.insert(Some(l), 0, Node::group(outer, vec![])).unwrap(); + d.insert(Some(outer), 0, Node::group(inner, vec![])).unwrap(); + d.insert(Some(inner), 0, path(a, 100.0)).unwrap(); + d.insert(Some(outer), 1, path(b, 300.0)).unwrap(); + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + for (smart_guides, snap_to_point) in [(true, true), (true, false), (false, true)] { + // The bounding box hidden: its corner handle sits on the anchor and would take the press. + let c = ToolContext { smart_guides, snap_to_point, show_bbox: false, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + let down = t.pointer(&c, &ev(PointerKind::Down, 103.0, 103.0)); + assert!(down.is_empty(), "smart guides {smart_guides}, snap to point {snap_to_point}: {down:?}"); + assert!( + matches!(t.state, State::Moving { hold, grip: Grip::Anchor, .. } if hold == Point::new(100.0, 100.0)), + "smart guides {smart_guides}, snap to point {snap_to_point}: {:?}", + t.state + ); + // The grabbed anchor follows the pointer: dragged to (301.5, 101), the anchor at (100, 100) + // lands on the other member's anchor at (300, 100). + let a = t.pointer(&c, &ev(PointerKind::Drag, 301.5, 101.0)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("smart guides {smart_guides}, snap to point {snap_to_point}: {a:?}") }; + let moved = (v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()); + assert!((moved.0 - 200.0).abs() < 1e-9 && moved.1.abs() < 1e-9, "smart guides {smart_guides}, snap to point {snap_to_point}: {moved:?}"); + } +} diff --git a/docs/dimensions.md b/docs/dimensions.md index bf6cf78653..4b30f44555 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -78,15 +78,36 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers tolerance of the level of a parallel line of a linear dimension already drawn has its line on that level. The other dimension, and every layer and group it is in, must be visible and unlocked. The tool reads at most 20,000 visible, unlocked layers, groups and objects, from the - frontmost back, so in a larger document a dimension past them is not a level. This is - VectorCraft's own rule. With + frontmost back, so in a larger document a dimension past them is not a level. A line that + moves off its level by more than 0.000001 pt across the span of both lines is not parallel. A + level that would put the line more than 1,000,000 pt from its points is passed over, and the + line goes where the pointer is. This is VectorCraft's own rule. With Smart Guides and Alignment Guides on, a guide runs along the level across both lines while the dimension is placed. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its radius, inwards its diameter. Clicking it gives its radius. Ellipses have no single radius. -- **Escape** or switching tools cancels a dimension being placed. +- **Moving a dimension:** the + [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) + describes repositioning a dimension by dragging it with the Dimension tool. With no points or + lines picked, a press within 8 pixels of what a dimension draws (its lines, arrowheads and + label), where it is the topmost object that can be edited, followed by a drag of more than 3 + pixels (8 pixels when the Linear tool finds an anchor, a corner of preview bounds or the end of a + dimension line within reach of the press) moves that dimension, as one undo step. A segment of the art + as near the press as the dimension's lines and label, or nearer, takes the press instead. The + line of a linear dimension moves as far across as the pointer moves; the arc of an angular one + moves as far as the pointer moves away from or toward the vertex, to no less than 12 points from + it; a radius or diameter line turns about the center as far as the pointer turns, or toward the + pointer when it was grabbed at the center. The dimension keeps what it measures and its link to + the art. Isolation mode applies as it does to a click: with a part of a dimension isolated, the + dimension is not dragged. A dimension that a geometry effect on it, on one of its parts or on a + group around it moves or distorts is not dragged, except in Outline view and on a layer whose + Preview is off, where effects are not drawn. With Smart Guides on, a linear dimension's line + lands on the level of a parallel dimension line, as when it is placed; when two such lines lie + on one level, the one nearer the pointer along it wins. A click there without a drag still picks a point. + How far the dimension moves is VectorCraft's own rule. +- **Escape** or switching tools cancels a dimension being placed or moved. **Tool Options** set the style of new dimensions: units (inches, millimetres, points, picas, pixels, centimetres, metres, feet, yards), precision (0–6 decimals), scale, the dimension and @@ -156,7 +177,10 @@ another document. line from the first point: along the left normal of a → b for an aligned dimension, downward for a horizontal one and leftward for a vertical one. A negative offset goes the other way. - `dimension.update`: restyle or move existing dimensions, or change the orientation of linear - ones. A new orientation keeps the line on the side of the points it was on. An update that + ones. A new orientation keeps the line on the side of the points it was on. `at: [x,y]`, applied + after `offset`, puts a linear dimension's line through the point, gives an angular dimension's + arc a radius of the point's distance from the vertex (at least 12 points), or turns a radius or + diameter line toward it, keeping what the dimension measures. An update that changes nothing records no undo step. - `dimension.applyToAll`: every dimension takes one dimension's style, in one undo step. - `tool.select {"tool":"dimension"}` and diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..3c577e0356 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1019,9 +1019,8 @@ as it is. When no object has one, `appearance.setItem` and `appearance.removeIte do for a row no object has, and the other commands are an error. The paint, stroke and gradient commands are also an error when the art's row is not the kind of row they edit, and `paint.editGradient`, `paint.setGradientGeom` and the `paint.freeform.*` commands without `stroke` edit the kind of the art's row. `appearance.moveItem`, `effect.move` and -`appearance.duplicateItem` with `to` are an error when the art's stack differs from the other objects', and -`appearance.duplicateItem` with `to` is also an error when two or more other objects are given, as it is without the -art. To change the art, edit the design with `graph.design`. +`appearance.duplicateItem` with `to` are an error when the art's stack differs from the other objects'. To change the +art, edit the design with `graph.design`. The graph also stores a paint or stroke weight that one of these commands changes on the topmost visible fill or stroke of a path directly in a series: a weight set with `stroke.set`, `stroke.weightUp` or `stroke.weightDown`; a gradient @@ -2350,7 +2349,7 @@ The transform, Align, Object Properties and Live Shape Properties commands refus that is not true or false with `` `strokes` must be true or false ``, naming the key, and leave the document and its undo history as they were: the options `copy`, `strokes`, `corners`, `patterns`, `objects` and `typeAreas` in `object.transform`, `object.move`, `object.nudge`, `object.rotate`, `object.scale`, `object.reflect`, `object.shear`, -`object.transformAgain` and `object.setBounds`; `anchors` and `releaseOutside` in `object.transform`; `big` in `object.nudge`; +`object.transformAgain` and `object.setBounds`; `anchors`, `releaseOutside` and `drawBehind` in `object.transform`; `big` in `object.nudge`; `absolute` in `object.rotate`; `proportional` in `object.setBounds`; `patterns` in `object.align`, `object.distribute` and `object.distributeSpacing`; `visible`, `locked`, `isolate` and `knockoutShape` in `object.setProps`; and `invertPie`, `makeSidesEqual` and `relativeRadii` in `object.setLiveShape`. A null is read as a key left out. @@ -2413,6 +2412,9 @@ and `amount` in `color.harmony`; `angle` in `paint.editGradient` and in the `gra `paint.freeform.splitLine`; `tolerance` and `gap` in `shapeBuilder.merge`; `gap` in `shapeBuilder.regions` and `shapeBuilder.copyRegion`; and `width` and `tolerance` in `livePaint.strokeEdge`. A null is read as a key left out. A gradient stop that names a swatch refuses a `tint` that is not a number with `` stop 0: `tint` must be a number ``. +`shape.flare` takes the rings' end point as both `x2` and `y2` or neither: given only one of them, with the other left +out or null, it answers `` missing number `y2` `` (or `` missing number `x2` ``), draws nothing and adds no undo step. +With neither, `pathLength` and `direction` place the end point. The Edit, document, guide and slice commands also check the type of each param and change nothing when one is wrong. A value that is not a number gets `` `dx` must be a number, not "10" ``: `dx` and `dy` in `edit.duplicate`, @@ -2430,11 +2432,15 @@ with `` `font` must be a string ``, and a `features` list with an entry that is `text.setStyle` and `text.setRangeStyle` refuse a `size` outside 0.1 to 1,296 pt with `` `size` must be from 0.1 to 1296 `` and change nothing. `type.ruby` refuses a `text`, `position` or `align` that is not a string, and `text.setPathHandle` refuses a `which` other than `in` or `out` with -`` `which` must be one of in, out ``. Each leaves the document, the selection and the undo history as they were, also -when the call gives another param it could apply. A null is read as a key left out. +`` `which` must be one of in, out ``. `text.editRange` refuses an `insert` that is not a string, `text.setText` a `text` +that is not a string, and `text.createInPath` a `mode` or `text` that is not a string, each with +`` `insert` must be a string ``, naming the key; `text.createInPath` refuses an `at` that is not two numbers with +`` `at` must be a point: [x, y] ``, in area mode too. Each leaves the document, the selection and the undo history as +they were, also when the call gives another param it could apply. A null is read as a key left out. A byte offset must be a whole number of at least 0. `at` in `text.startList`, and `start` and `end` in -`text.editRange`, `text.getRange` and `text.setRangeStyle`, and in `type.step` and `addon.type.textTweaker` given an `id`, +`text.editRange`, `text.getRange` and `text.setRangeStyle`, `start` in `text.touchType`, `text.glyphAlternates` and +`text.setGlyphAlternate`, and `start` and `end` in `type.step` and `addon.type.textTweaker` given an `id`, refuse a negative or fractional number with `` `at` must be a whole number ``, naming the key, and change nothing. `2.0` is read as `2`, and a null as the key left out. @@ -2558,7 +2564,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, + File object's `length`, `hidden` or `readonly` counts too, on any object that may be a File object; only + `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, @@ -2935,9 +2942,19 @@ VectorCraft reads files by these rules of its own: folder gives `null` with `Script folder mask takes too many steps to match`. - A path longer than 32,767 characters throws a `RangeError` (`Script file path exceeds 32,767 characters`) when a `File` or `Folder` is made from it. -- `createAlias` returns `false` with `Script files cannot make aliases`, setting `hidden` sets `error` to `Script - file hidden setting cannot be changed` and changes nothing, and `execute` opens nothing and returns `false`. In the - web build every lookup fails with `Script file access is unavailable on the web`. +- On Unix a file is hidden when its name starts with a dot. Setting `hidden` renames the file in its folder with one + dot added, or with its leading dots taken off, under the rules for `rename`, and the object takes the new path, + where a file it has open stays open; a + file already as asked keeps its name, and a name of dots alone or a folder gives `false` with `error` set. + `createAlias(target)` makes a symbolic link at the object's path to a file, a path or a `File`, and returns `true`; + the link leads to the file's real path. On Windows setting `hidden` sets `error` to `Script file hidden setting + cannot be changed`, `createAlias` returns `false` with `Script files cannot make aliases`, and neither changes + anything. `execute` opens nothing and returns `false`. In the web build every lookup fails with `Script file access + is unavailable on the web`. +- `alias` is true for a link and `resolve()` gives the file it leads to, and reading or writing through the link reads + or writes that file. `hidden` tells whether the link's own name is hidden, and setting `hidden`, `rename` and + `remove` change the link and not the file it leads to, as the help page describes + (). The help page's writing members work as it describes (, @@ -2981,6 +2998,14 @@ VectorCraft writes files by these rules of its own: been made, apart from the script's own `Folder.userData`, and a folder that holds it cannot be renamed. Anything else gives `false` with `Script file access denied`. +- Setting `hidden` needs both the old and the new name to be places the script may write. `createAlias` needs the + link's place to be one the script may write where nothing is, not even a link that leads nowhere (`Script file + name is already in use`), and the file it leads to to be one the script may read, never a folder (`Script file is + not a regular file`) or a file that is not there (`Script file does not exist`). A link is looked up again each + time it is used: one that leads out of the script's places afterward is refused like any other path, and writing + through a link needs the file it leads to to be a place the script may write. When a folder above the link's place + is replaced by a link while the alias is made, the new link is removed again and `createAlias` gives `Script file + access denied`. - What a script writes is written when it closes the file or when the run ends, also when the run fails. At the run's end the files left open are written in the order they were opened. A file that `close` could not write stays open, so a later `close` tries again, and is written again when the run ends; a @@ -4857,7 +4882,9 @@ already walks Image Trace. Short agent entry points: `tool.setOption {tool: "eyedropper", values: {stop: "livePaintBucket"}}`): the stop stays selected, and the click's `paint.sampleColor {color, stop}` recolors that stop of the bucket's gradient and leaves the selection's paint as it is. Once that stop is no longer selected (a Cmd/Ctrl-click selected another - object), the next click ends the pick without sampling and switches back to the bucket. + object), the next click ends the pick without sampling and switches back to the bucket. The bucket's colors have no + freeform points: `paint.freeform.get`, and `paint.freeform.selectPoint` with an `index`, report an error, and so do + the other `paint.freeform` commands without `ids`, `id` or `item`, which then leave the selection's gradient as it is. With the Live Paint Bucket selected and no drag in progress, Left and Right without Shift, Alt or Cmd/Ctrl (which keep their shortcuts) run `paint.setFill {swatch, ids: []}` (or `paint.setStroke` when the Stroke proxy is in front) with the color swatch before or after the active paint in the @@ -5810,7 +5837,21 @@ From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes -in under a numbered name ("Ink 2") and the pattern links to that. A document with +in under a numbered name ("Ink 2") and the pattern links to that. That numbered name skips the names the library +gives its other swatches. A library color whose name the document gives +another color is the document's numbered copy of the same color when it has one, so adding the pattern and its color +again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name +is used as it is. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the +document as such a numbered copy, links to that copy, whether the color is picked before or after it, was added +earlier or came with a pattern's art. A library global color is not the document's process color of the same name and +paint: it comes in numbered. A global or spot color that a library tint or gradient links to and the document lacks +comes in with the tint or gradient, under a numbered name when the document gives its name another swatch. The +document's tint or gradient of the library one's name is that swatch when it links to the copy of the color that the +art of a pattern picked with it takes; a numbered copy that the library also names stands for that library swatch +otherwise. When the document's tint or gradient links to a color the document no longer has (deleted without +unlinking), that color comes back under its own name. A pattern is found again when it was pasted with Add or Merge for all of its colors; one pasted +with Merge for some colors and Add for others is added again as a copy. `added` lists the colors the pattern's art, a +tint or a gradient brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. @@ -6023,8 +6064,11 @@ swatch, else `Gradient`; `library.use` paints the selection's fill or stroke wit (else the default one, or the pattern swatch `swatch`) with the images, symbols, patterns, swatches, styles and brushes its art uses, and a thumbnail of one swatch's worth of it; `library.use` adds the pattern and its swatch to the document (the same pattern there is reused, and a name the document gives another pattern gets a number) and paints the selection's -fill or stroke with it, as one undo step, and returns the pattern's name in the document as `pattern`. `library.get` -lists them as `gradients: [{name, gradient}]` and `patterns: [{name, pattern, thumbnail}]`. +fill or stroke with it, as one undo step, and returns the pattern's name in the document as `pattern`. A global or spot +color the pattern's art links to keeps the item's color, as with `swatch.library.add`: when the document gives its name +another color, it comes in under a numbered name ("Ink 2"), or as the document's numbered copy of the same color, and +the pattern links to it. A pattern the document holds with its art linked to the document's own color of that name is +reused. `library.get` lists them as `gradients: [{name, gradient}]` and `patterns: [{name, pattern, thumbnail}]`. Items can be put in user-named groups, which the panel shows as collapsible sections after the ungrouped items (its search field filters every item by name; `library.get` lists them all to filter). `library.createGroup {library?, @@ -6171,6 +6215,9 @@ and `height`, so a new `hSpacing` changes the tile's width. `pattern.options` st `height` that is not a positive number, such as `"width": 0`, and changes nothing. Without a `name`, `object.pattern.edit` edits the pattern that fills or strokes a selected object, and `pattern.options` changes the pattern being edited; each returns an error when there is no such pattern. `pattern.delete` requires `name`. +`object.pattern.make`, `object.pattern.replaceArt`, `object.repeat.radial`, `object.repeat.grid` and +`object.repeat.mirror` return the error "no such object id N", and change nothing, when an `ids` entry names no object, +even when the other entries name objects. With `pattern.options {moveTileWithArt: true}` (Move Tile with Art), a move of all of the tile art in pattern editing mode moves the tile by the same offset: `object.move`, `object.nudge`, `object.transform` with a translation, and drags @@ -6207,7 +6254,8 @@ editing the pattern first". While a mask is edited, `object.pattern.edit` and `o Pathfinder Options: `object.pathfinder.options {precision?, removeRedundantPoints?, removeUnpainted?}` (or `prefs.get`/`prefs.set` with key `pathfinder`) reads and sets the options every later Shape Mode and Pathfinder -operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit also reads) is how closely results follow +operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit or a string that is all one number also reads, and +any other string, such as `"1abc"`, is an error) is how closely results follow the paths (they are refit to within it and pieces thinner than it are dropped), `removeRedundantPoints` takes the anchors that don't change a result's shape off it, and `removeUnpainted` makes Divide and Outline leave out the pieces of objects with no fill (or only hidden fills). Both default to false; `{}` reads the options. Each Shape Mode and @@ -6278,7 +6326,9 @@ Alt+Shift-click samples only the color at the pointer into the active paint defa sets them; a tree names flags under `appearance` (`transparency`, `fill` `{color, transparency, overprint}`, `stroke` `{color, transparency, overprint, weight, cap, join, miter, dash}`), `character` and `paragraph`, and a bool for a branch sets all of it. `paint.sampleColor {color}` puts a sampled color into the active proxy (in a CMYK document an -RGB color is stored as CMYK, as `paint.setFill` stores it). Clicking an image samples its pixels: a CMYK image (a +RGB color is stored as CMYK, as `paint.setFill` stores it). `paint.sampleColor {color, stop}` recolors that stop of +the gradient behind the proxy; with objects in `ids` it recolors that stop in the topmost fill (or stroke) gradient of +the first object `paint.editGradient` edits for them, whatever tool is active. Clicking an image samples its pixels: a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's sRGB pixel is taken into the working RGB space. @@ -7062,6 +7112,14 @@ VectorCraft's own values. `` `width` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is recorded. Left out or null, `width` is 8 pt. The range is VectorCraft's own value. +`path.smoothRegion` (the Smooth tool) refuses a `radius` outside 0.001 to 1000 pt with +`` `radius` must be from 0.001 to 1000 `` and a `fidelity` outside 0.000078125 to about 3195 pt (the Smooth tool's +0.05 to 100 px at the highest and the lowest zoom) with `` `fidelity` must be from 0.000078125 to 3194.8881789137376 pt ``. +`path.joinScrub` (the Join tool) refuses a `tolerance` outside 0.001 to 1000 pt with +`` `tolerance` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is +recorded. Left out or null, `radius` is 12 pt, `fidelity` is 2.5 pt and `tolerance` is 12 pt. The tools send these in screen +pixels divided by the zoom, kept within the ranges. The `radius` and `tolerance` ranges are VectorCraft's own values. + These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: `independent` in `path.close` and `path.setHandle`; `symmetric` and `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and @@ -7113,8 +7171,10 @@ result and the original path stay within `tolerance` of each other, except that is dropped, so a small circle in a compound path can be removed at a large `tolerance`. A segment that would need more than 65,536 samples at that tolerance stays as it is, and so does a segment after a run's first 16,777,216 samples or 2,097,152 result segments. With `straightLines`, such a segment becomes evenly spaced lines, up to 65,536, and past those -limits the lines can be farther than `tolerance` from the segment. With `level` or `auto`, the reply also has the `level` -used: +limits the lines can be farther than `tolerance` from the segment. A closed path keeps its start, where its dashes +begin: it starts at its old first anchor when the refit keeps an anchor there, otherwise at a new anchor where the refit +passes nearest that point when the result with that anchor still has fewer anchors than the path had, and otherwise at +the refit's anchor nearest that point. It runs the same way around as before. With `level` or `auto`, the reply also has the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} @@ -7123,7 +7183,8 @@ used: With segments of a path direct-selected (`select.segments`, or `select.anchors` with both anchors of a segment), Simplify refits only each run of consecutive selected segments, between the run's end anchors: they stay where they are, with their handles on the side away from the run, and every other anchor and segment of the path stays exactly as it was. A -closed path's run may cross its start point; the path then starts at the run's end anchor. Separate runs on one path +closed path's run may cross its start point; the path then keeps its start as a whole path does, with the new start on +that run. Separate runs on one path simplify independently, in one undo step, and the runs stay direct-selected (as segments when segments were picked). A path with only lone anchors selected, and every path with `wholePaths: true`, simplifies whole: @@ -7151,7 +7212,7 @@ side) to 100 (maximum smoothing); `auto: true` (Auto-Smooth) uses level 50, the its length (by up to 5% of its longer side; none at level 0) and refitted with curves within 0.1% to 2.5% of it, keeping a corner only where it turns back on itself, so bumps, jags and kinks become one curve; with anchor points or segments of a path direct-selected (and no `ids`), only the sections between them are smoothed, as Simplify does. A refit never has more anchor points than the path had, so a shape whose corners the tolerance can't -round, such as a rectangle, stays as it is. Closed paths stay closed and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: +round, such as a rectangle, stays as it is. Closed paths stay closed and keep their start as Simplify keeps it, and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.smooth","params":{"level":80}}} @@ -7161,8 +7222,10 @@ round, such as a rectangle, stays as it is. Closed paths stay closed and open pa reaches the first or last anchor of an open path, the curve there leaves or arrives along the smoothed path within `radius` of that end rather than along the first or last segment, so a jagged end turns with the rest of the path; it keeps the segment's direction when the smoothed path there turns back by 90° or more. Where the stretch ends inside a -path, the curve keeps the direction of the part outside the drag. `object.path.smooth` and Simplify keep each end's -direction. +path, the curve keeps the direction of the part outside the drag. A segment leading out of the stretch that is within +`radius` of the drag for no more than 1/64 of `radius` from the stretch's anchor is left as it is, and the stretch ends +at that anchor, so a call that reaches an anchor an earlier call added at the edge of its reach does not split the +segment beyond it again (the 1/64 share is VectorCraft's own value). `object.path.smooth` and Simplify keep each end's direction. `path.smoothRegion` keeps an anchor as a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) at the anchor and also over `radius` and over twice `radius` on either side of it (on a closed path that the drag reaches all the @@ -7270,8 +7333,10 @@ it touches and, with Measurement Labels on, its radius by the pointer, followed radius. A click draws the circle, and a press dragged 2 screen points or more, or canceled with Escape, draws nothing; Shift held at the press puts the circle on the other side of the path. On a straight segment, at a cusp, at a corner anchor, or where the circle would reach past the canvas, the pointer shows "Straight segment", "Cusp", "Corner" or -"Circle too large", and a click draws nothing. The pointer passes over the circles the tool drew until another tool -is chosen or an edit, Undo or Redo is made outside the tool. +"Circle too large", and a click draws nothing. The pointer passes over the circles the tool drew until Deselect or a +selection made outside the tool leaves none of them selected, another tool is chosen, another document becomes +active, or an edit, Undo or Redo is made outside the tool. Selecting one of them again does not put it back out of +reach. ```json {"name":"run_command","arguments":{"command":"shape.curvatureCircle","params":{"id":12,"segment":0,"t":0.5}}} @@ -7328,6 +7393,21 @@ arc size of 180°, its 15° steps, the side an arc bulges to, what C and `[` `]` path are VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences (`tool.setOption {tool: "quickPen", key, value}`). +While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a protractor around the arc's +center: a tick across the arc's circle every 15° from where the arc starts, a longer tick every 90°, and one where the +arc ends. The piece the next click adds shows its protractor only while Enable Rubber Band for the Pen tool shows +that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same +circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the +point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc, and a continuous arc that +starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. Alt tapped +during a press moves the piece's end for the new action at once: off the tick when a continuous arc becomes a +sharp-corner arc, and onto it when the piece becomes a continuous arc. After a snap +setting (Smart Guides, Snap to Point, Snap to Grid, Snap to Pixel or a snapping tolerance) changes under a still +pointer, the hover's preview, its protractor, its distance label and its Smart Guides are hidden until the pointer +moves. When the view, the document or the selection changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, so it +does not change the tick snapping. The +protractor, its 15° step and the tick snapping are VectorCraft's own behavior. + Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, Flip Arc flips the last sharp-corner arc as C does (`tool.quickPen.flipArc {}`, which first finishes any pending tool edit, which can change the document, then returns false and changes nothing more when the Quick Pen tool is not active @@ -7578,8 +7658,8 @@ written as the nearest parallelogram. Ordinary groups and layers do not count to writes an image nested deeper. Corners that would fold the image over itself, put three corners on one line, join two corners, cross the warp's horizon or lie too close together for a perspective map are an error, and nothing changes. A transform that squeezes the corners past what a perspective map -can place leaves the image at the parallelogram nearest them. A file whose `image_quad` holds other than four points, -or breaks these rules, opens with the image placed by its transform. A drag is one undo step, and a distort that leaves +can place leaves the image at the parallelogram nearest them. A file whose `image_quad` is not a list, holds other than four points +(an entry that is not a point included), or breaks these rules, opens with the image placed by its transform. A drag is one undo step, and a distort that leaves the corners where they are records none. Image info (`image.info`) gives a distorted image's resolution at its middle, and Link Info (`links.info`) gives its scale and rotation there. @@ -9153,7 +9233,12 @@ too: in Draw Inside, `edit.paste`, `edit.pasteInPlace` and `edit.pasteOnAllArtbo object drawn into (its clip group, made on the first paste), whatever Paste Remembers Layers says; in Draw Behind, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put them just below the selection, and a placed symbol instance (`symbol.place`) goes just below the selection too. `edit.pasteInFront` and -`edit.pasteInBack` ignore the drawing mode. When the object drawn into is the one isolation mode isolates (`object.isolate`, +`edit.pasteInBack` ignore the drawing mode. In Draw Behind, an Alt-drag (Option-drag on macOS) of whole objects with +the Selection or Direct Selection tool puts each copy directly below its own original, in the original's group or layer, +and selects the copies: the tools send `object.transform` with `copy` and `drawBehind: true`. The copy of the clipping +path of a clip group or a clipping layer goes directly above it, so the clipping path stays the bottom object. Without `drawBehind`, and +in Draw Normal and Draw Inside, the copies go directly above; `object.move` and the transform dialogs' Copy, +`edit.duplicate` and `object.transformAgain` put them above in every drawing mode. When the object drawn into is the one isolation mode isolates (`object.isolate`, or a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so the new art can be picked and isn't dimmed; `edit.undo` or `edit.redo` that removes the isolated object ends isolation mode. @@ -9899,7 +9984,8 @@ file is missing stays linked: relink it first); `links.unembed {id, path}` write (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD or PSB file written as stored (PNG, or TIFF for a CMYK file), with `path` or `folder`, keeps the clip group of the clipping path that file names, and the file written keeps the path: Open, Place, Relink and Update Links read the file -with its clip group. +with its clip group. A clipping mask released, edited or made in the document stays as it is, whatever format the +image is written in. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo @@ -10556,8 +10642,9 @@ ignored. Deleting every opaque color is an error, and the settings, preview and entry of transparent pixels cannot be deleted. `colorTable.customPalette: ["#rrggbb"…]` is a fixed palette (a Custom table) used instead of the reduction's own, at most `colors` entries with the transparent one included, so a color it lacks is not made again. Its colors in `transparent` all become the transparent entry and take one of the `colors` -slots together (when no pixel is transparent and no pixel takes one of them, that slot goes to its next color); its -other colors fill the remaining slots in order. The dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold +slots together (with transparent pixels they share those pixels' slot; when no pixel is transparent and no pixel takes +one of them, that slot goes to its next color), and the preview's `mappedToTransparent` lists each of them a pixel +took; its other colors fill the remaining slots, its shifted colors first, then its locked ones, then the rest in order. The dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold at most 256 colors, and `#rrggbbaa` is refused. A `reduction` change without `colorTable` in the same params clears both lists. JPEG and PNG-24 have no color table and do not read them. Presets and `webExport.settings` keep them. In the dialog a click selects one color, Shift-click selects the colors between it and the last one clicked, and @@ -10872,8 +10959,8 @@ clipping mask into one layer and discards hidden layers that require merging; th imports one image, and Import Hidden Layers brings hidden layers in. `document.open` does the same, with `layers: false` for the single image and `hiddenLayers: true` for the hidden layers. The page also merges adjustment layers, layers with a knockout option, and layers that hold transparent pixels in some blend modes with -the layers below them. `document.open` does not apply adjustments, applies only shallow knockouts inside groups, and -otherwise merges a layer by its blend mode alone, as the rules below say. +the layers below them. `document.open` applies only Invert, Threshold and Posterize adjustments, applies only +shallow knockouts inside groups, and otherwise merges a layer by its blend mode alone, as the rules below say. The rest are VectorCraft's own rules: @@ -10909,10 +10996,28 @@ The rest are VectorCraft's own rules: stores. A solid color fill layer that stores no pixels and has no vector mask comes in as an image of its color (RGB, CMYK, Grayscale, Lab or HSB) over the canvas. One whose shape is a vector mask isn't drawn, and the layers clipped to it are left out. -- Adjustment layers, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on, - the other knockouts (top-level layers, clipped layers, layers that others are clipped to, Pass Through groups with - layers in other modes, other Knockout values, and merges that need more memory than allowed) and vector masks are - not applied; the `warnings` count them. +- An Invert, Threshold or Posterize adjustment layer (`nvrt`, `thrs` and `post` in the PSD file format + specification) is merged with the visible layers below it in its group, which it changes. Clipped to a layer, it + changes only that layer and the layers clipped to it. Each color channel is taken as an 8-bit sRGB value: Invert + turns `v` into `255 − v`; Threshold makes a pixel white when its luminance (Rec. 709 weights on linear sRGB, + encoded back to 0..255) is above the level (1 to 255) and black otherwise; Posterize maps each channel to the + nearest of its 2 to 255 evenly spaced levels, the higher one on a tie. The adjusted color is composited over the + color below in the layer's blend mode, at its opacity times its fill opacity, through its layer mask, and + transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer + that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all + transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such + layers, nor a layer or group whose layer mask hides all of it, for a layer a mask of 0 over each of its pixels that + isn't fully transparent, for a group the same over its layers' pixels, or a mask of 0 everywhere when it holds an + adjustment layer or a fill that stores no pixels, and for a layer with layers clipped to it the same as for the + layer) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, + and a clip, or a merge for another layer, that it is part of goes on without it. +- Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to + another adjustment layer, whose data can't be read (a level out of range, too short, or two adjustment blocks on + one layer) or whose merge, its layer mask included, needs more memory than allowed, fill layers that store no pixels and whose fill isn't + read, layer effects that are switched on, the other knockouts (top-level layers, clipped layers, layers that others + are clipped to, Pass Through groups with layers in other modes, other Knockout values, and merges that need more + memory than allowed) and vector masks are not applied; the `warnings` count them. - Layer channels may be raw, PackBits or zipped (with or without prediction) at 8, 16 and 32 bits. - A file without layers opens as its merged image. A file whose layers can't be read opens as its merged image with a warning, and when the merged image can't be read either, the file is refused with an error. @@ -11456,8 +11561,9 @@ at a leftover distance of 0.05. A compound path that holds several glyphs, such as a word made into one compound path, is split into groups of contours (a contour with the contours inside it) in path order, and runs of up to three groups are matched, the longest first among those after which the remaining groups can still all be matched, so an i's stem and dot become one i. A group whose contours run the other -way round, as Make Compound Path leaves some of them, still matches exactly. Exact matches of the whole shape come -first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The +way round, as Make Compound Path leaves some of them, still matches exactly, and so does one where only some of its +contours run the other way round (in an even-odd compound, an o's counter and not its outer contour). Exact matches +of the whole shape come first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in `unmatched` when another shape of the selection becomes type, and the command returns an error when no shape does. A glyph also has to paint the area the shape paints under the shape's fill rule: a compound filled by the nonzero rule @@ -13275,7 +13381,8 @@ runs: `plugin.install`, `plugin.run`, `plugin.reload` and exporters return an er object's geometry unchanged while the object keeps the effect: `effect.list` gives that effect `skipped: true`, and the Appearance panel shows "(Safe Mode)" after its name and the plug-in's id in its tooltip. `effect.expandAppearance` returns an error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. That includes a -plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. `vectorcraft` rejects an option it does not know (such as +visible plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. A +hidden instance, or one in a template sublayer, draws nothing in that image, so its symbol's art does not count. `vectorcraft` rejects an option it does not know (such as `--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled, pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or diff --git a/docs/plugins.md b/docs/plugins.md index 7e6dd26185..ab294db1ff 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -129,14 +129,14 @@ defaults): | Module size | 32 MiB | rejected | | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | -| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | -| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | +| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte; [storage calls](#settings-and-cache) take one more for every 64 bytes they move | `Limit("instruction budget")` | +| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions and after each [storage call](#settings-and-cache); the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | | Module shape | wasmi's strict limits (≤ 10,000 functions, 1 memory, …) | rejected | An export runs where the export runs: with Background Export on, on the export's worker, whose Cancel stops the -plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the +plug-in between two of those 20 M-instruction slices or after a storage call; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. ### Instruction budget preference @@ -151,7 +151,7 @@ and MCP alike: A [heavy filter](#heavy-filters) keeps its 1 G and 300 s with either choice. Live effects, exporters and importers keep their own budgets. A change applies to the next run of every installed filter, without installing it again. Cancel and -the time budget stop a run between two 20 M-instruction slices with either choice. `prefs.set {key: +the time budget stop a run between two 20 M-instruction slices, or after a storage call, with either choice. `prefs.set {key: "pluginInstructionBudget", value}` takes `normal` or `large` (or the labels Normal and Large) and refuses any other value; a saved preferences file with another value reads as Normal. @@ -428,6 +428,14 @@ its 10,000 storage calls or its 1 GiB of storage reads and writes. Each call cou settings call counts the whole settings file when it reads the file, and a set or delete also counts the whole file when it writes the file; a cache call counts the entry it reads or writes. A read counts them even when the value doesn't fit and nothing is copied. A call that would pass the 1 GiB returns `-7` before it reads or writes anything. +The bytes the calls count also cost the run one instruction of its budget for every 64 bytes (VectorCraft's own +value), counted over the whole run, so the 1 GiB costs about 16.8 M instructions. A get also pays at that rate for the +bytes it copies into the module's memory that it didn't count, such as a value answered from memory. A call stops +before a read or write of a file that the run's instructions can't pay for, and the run ends with +`Limit("instruction budget")`; a set or delete may already have read the settings file then. A call takes +instructions beyond the current 20 M-instruction slice only before Cancel and the time budget; after either, a read or +write that needs them doesn't happen. After every storage call the run checks its time budget and Cancel, and stops +if either has come. A read or write that would pass the 1 GiB still returns `-7`, whatever the instructions left. The app keeps the settings in memory after the first call and reads `settings.json` again only when the file's size or modified time differs from the last read or write. A get answered from memory reads no file and counts no bytes. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3da663c191 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,6 +642,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. @@ -690,6 +691,7 @@ since 2026-10-01. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. **Drawing tools, Dimension tool points on preview bounds corners (#8537):** With Use Preview Bounds on, a Linear point can land on a corner of the preview bounds of a path or compound path with a stroke or effects; the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes measuring a stroked segment by snapping onto its preview bounds. By VectorCraft's own rule, only the four corners are snapped to: a click within 8 pixels of a corner lands on it instead of on the anchor at the same corner of the object's geometric bounds, and any other anchor nearer the pointer takes the point; for an object that is not rotated, a horizontal or vertical dimension between two such corners measures, when it is drawn, the size that W and H show. The edges of the preview bounds, a group's own strokes or effects, type and paths made into guides are not snapped to. `with_preview_bounds_points_land_on_the_corners_of_the_stroke`, `preview_bounds_corners_take_picks_as_anchors_do`, `a_corner_takes_only_the_anchor_it_stands_for`, `a_point_is_held_for_a_corner_only_when_picked_on_it` and `hovering_a_corner_of_the_preview_bounds_shows_the_anchor_ring` cover it. **Drawing tools, Dimension tool lines line up with dimensions already drawn (#8063, #5590):** By VectorCraft's own rule, with Smart Guides on, a linear dimension placed with its line within the Smart Guides snapping tolerance of the level of a parallel line of a visible, unlocked linear dimension already drawn has its line on that level, and with Alignment Guides on a guide runs along the level across both lines while it is placed. `a_dimension_line_placed_beside_another_lands_on_its_level`, `a_dimension_line_on_another_level_shows_one_guide_across_both`, `a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer`, `a_dimension_dragged_out_beside_another_lands_on_its_level` and `a_line_the_pointer_lies_across_wins_on_one_level` cover it. +**Drawing tools, Dimension tool moves a dimension already drawn:** As the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes, a drag with the Dimension tool from a dimension already drawn repositions it, as one undo step, keeping what it measures and its link to the art. By VectorCraft's own rule, the part grabbed follows the pointer: a linear dimension's line moves as far across as the pointer moves, an angular arc moves as far as the pointer moves away from or toward the vertex, and a radius or diameter line turns about the center; the press must be where the canvas hits the dimension, within 8 pixels; with Smart Guides on, a linear dimension's line lands on the level of a parallel dimension line. `dimension.update` takes `at`. `dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line`, `a_dimension_moved_beside_another_lands_on_its_level`, `a_dragged_dimension_follows_the_part_grabbed`, `a_dimension_is_dragged_only_where_the_canvas_hits_it` and `dimension_update_at_moves_the_line_through_the_point` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. **Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `each_arrow_style_draws_its_stroke_arrowhead_at_both_ends` cover it. **Drawing tools, Dimension tool Arrow Style offers every stroke arrowhead (#8049, #3222):** By VectorCraft's own rule, Arrow Style lists Filled, Open, Tick and None, then the other 38 built-in Stroke panel arrowheads, each with its drawn preview. The options save the head in `arrowHead` (`Barbed`) and keep `arrowStyle` at `filled`, so versions that have the stroke arrowhead but not `arrowHead` keep the saved arrows until they draw the dimension again and then draw Filled arrows (versions without the stroke arrowhead do not open the file); documents and tool settings saved before open unchanged. `every_stroke_arrowhead_draws_as_a_dimension_arrowhead`, `arrow_style_shows_a_stroke_arrowhead`, `arrow_style_list_names_each_style_once` and `built_in_arrowhead_names_are_in_complete_catalogs` cover it. @@ -946,6 +948,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. - **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. +- **Text command parameter errors:** `text.editRange`'s `insert`, `text.setText`'s `text` and `text.createInPath`'s `mode` and `text` must be strings, `text.createInPath`'s `at` must be two numbers, and `start` in `text.touchType`, `text.glyphAlternates` and `text.setGlyphAlternate` must be a whole number of at least 0. A wrong value is an error naming the parameter, and the document and undo history do not change; null is read as the parameter left out. Pathfinder `precision` takes a number, a string that is all one number or a length with a unit, and refuses a string such as `"1abc"`. This is VectorCraft's own rule; no score changes. Tests: `tests::textedit::text_edits_refuse_a_param_of_the_wrong_type` and `tests::pathops::pathfinder_options_round_trip_and_refuse_bad_values` in `vectorcraft-engine`. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. @@ -1040,6 +1043,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. @@ -1071,12 +1075,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. - Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`). - - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). + - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. + - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. @@ -1309,6 +1314,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - An Alt-click (Option-click on macOS) with the Flare tool draws a flare centered at the click at once, without opening the Flare Tool Options, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describes for a default flare. As VectorCraft's own rules, the flare takes the tool's current options (the defaults until they are changed), Alt counts when it is held as the button goes down, a drag with Alt still draws the flare in two stages, and on the active perspective plane the flare is the one the click dialog's OK draws there (`alt_click_draws_a_flare_with_the_options_at_once`, `alt_click_draws_on_the_active_perspective_plane`, `an_alt_click_with_the_flare_tool_draws_the_flare_the_click_dialog_draws`). - While a flare's center is dragged out, Ctrl (Command on macOS) keeps the center's size and the drag sizes the halo; while its rings' end point is placed, Up/Down Arrow add and remove rings and ~ places them anew (`shape.flare`'s `ringSeed`) ([Draw and edit flares](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-and-edit-flares.html); `flare_arrows_change_the_rays_then_the_rings`, `flare_tilde_places_the_rings_anew`, `flare_ctrl_keeps_the_center_and_the_drag_sizes_the_halo`). - Flare ring placement accepts small `ringSeed` values, including 0, without concentrating the first ring at the center; the same seed and parameters reproduce the same positions. This seed mapping is VectorCraft's own (`flare_small_ring_seeds_spread_the_first_ring_along_the_path`, `flare_ring_seed_moves_only_the_rings`). + - `shape.flare` takes the rings' end point as `x2` and `y2` together: one given alone is an error that draws nothing and adds no undo step, and with neither, `pathLength` and `direction` place it. Saved flare settings that hold only one of them are not read as an editable flare. These are VectorCraft's own rules (`flare_requires_both_endpoint_coordinates`, `flare_omitted_or_null_endpoint_coordinates_use_path_fallback`, `flare_settings_with_a_lone_endpoint_coordinate_are_not_a_flare`). - A plain step of a number field (Up/Down or a wheel notch) goes to the next whole unit in its direction and a Ctrl/Cmd step goes to the next tenth, so 5.1 mm steps up to 6 mm and down to 5 mm (#2881). A Shift step adds or takes ten and keeps the fraction. - In the number, text and color fields of the panels and the Control bar, Shift+Enter (Shift+Return) applies the value and keeps the field active with its value selected; a text box of several lines takes it as a line break. In a dialog, Shift+Enter applies the value and confirms the dialog, as Enter does. - The Pattern Options panel's Name field and the name fields that a double-click opens in the Layers, Artboards and Asset Export panels take Shift+Enter (Shift+Return) the same way: it applies the name and keeps the field active with the name selected. @@ -1423,7 +1429,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, the copy of the clipping path of a clip group or a clipping layer goes directly above it so the clipping path stays the bottom object, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). @@ -1461,6 +1467,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). `path.eraseRegion` refuses an Angle outside −180° to 180° and a Roundness outside 1% to 100% with an error and leaves the document unchanged; a key left out or null takes its default (0° and 100%). The help page gives no range for the two options, so the ranges are VectorCraft's own values. `path.split` refuses a `t` outside 0 to 1 in the same way. `path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with an error and leaves the document unchanged; left out or null, the width is 8 pt. The help page gives the Path Eraser no width option, so the range is VectorCraft's own value. + `path.smoothRegion` (the Smooth tool) refuses a `radius` outside 0.001 to 1000 pt or a `fidelity` outside 0.000078125 to about 3195 pt with an error naming the key, and `path.joinScrub` (the Join tool) refuses a `tolerance` outside 0.001 to 1000 pt the same way; the document does not change; before, a radius or tolerance below 0 was read as 0 and a fidelity was moved into its range. Left out or null, the defaults stay (12 pt, 2.5 pt and 12 pt), and the tools keep what they send within the ranges at any zoom. The radius and tolerance ranges are VectorCraft's own values (engine `smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range`). Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). Eraser Tool Options show the Blob Brush's tip preview under the Roundness rows. A drag on the arrowhead turns the Angle, and a drag that starts on a black dot moves it toward the center for a flatter tip or away from it for a rounder one, as the Eraser tool options section of the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133) describes; the fields show the new values, and OK keeps them. The drag's mapping and the Angle and Roundness sliders are the Blob Brush preview's, which are VectorCraft's own, with the Eraser's Roundness range of 1% to 100% for the drag and the keys. The preview shows the set Angle and Roundness, not a Random or pen-driven variation of them. Regression tests: `dialogs::tests::the_eraser_tip_preview_sets_the_angle_and_roundness_by_dragging`, `dialogs::freehand::tests::a_roundness_dot_keeps_the_eraser_at_one_percent_or_more`. The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). @@ -1552,6 +1559,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. + A segment leading out of the stretch a Smooth drag smooths that is in the drag's reach for no more than 1/64 of the reach from the stretch's anchor is left as it is, and the stretch ends at that anchor, so a drag that reaches an anchor an earlier drag added at the edge of its reach does not split the segment beyond it again or leave a corner there (`path.smoothRegion`). The 1/64 share is VectorCraft's own value (`tests/draw2.rs`, `smooth_drags_again_and_again_along_part_of_an_ellipse_add_no_anchors_or_corners`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). @@ -1687,7 +1695,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`). - The solids of one Extrude & Bevel (both kinds) or Inflate effect on one object, its fill's, its strokes' and a group's members' together, keep up to 163,840 faces (VectorCraft's own limit). Each solid is built in turn; once their faces pass the limit, no later solid is built, the object draws its source art, and applying or editing the effect, Export 3D Object and Expand as Wireframes report that the 3D surface is too complex. Tests `solids::tests::an_objects_solids_count_their_faces_together`, `a_groups_solids_together_past_the_limit_draw_the_source`, `a_fill_and_strokes_together_past_the_limit_draw_the_source`. - Inflate at a Volume of 0 % works out each shape's puff only when its solid is built, so no puff is worked out for the shapes after the face limit stops, and the solids are the same bit for bit; with any volume every puff is worked out first, as the highest one places the eye. The shadow builds no solid for a fully transparent fill or stroke. Tests `solid::tests::a_flat_inflate_solves_each_puff_as_its_solid_is_taken`, `a_flat_inflate_solved_as_taken_matches_one_solved_first`, `shadow::tests::an_inflate_shape_that_casts_nothing_builds_no_solid`. - - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. + - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. A piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. + - The edges of Extrude & Bevel's walls and bevels between two bevel steps or two wall slices follow the art's curves too, the same curves on both faces that meet there; a twist cuts a wall's edge at points of the curve, so each piece meets the cap along its curve, a bevel's inset cap included; and Inflate keeps the curves of its flat back, its side walls, and its front and puffed back along the outline (within the sampling tolerance there). Tests `solid::tests_curves::interior_bevel_edges_keep_the_curves_of_the_art`, `a_twisted_wall_keeps_curves_where_a_twist_cuts_it`, `twisted_bevel_pieces_meet_the_cap_at_sharp_joins`, `inflate_keeps_the_curves_of_its_outline`, `straight_tiny_and_twisted_solids_keep_their_curves_bounded`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). The graphics wrapped around Revolve's side export the same way, as a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles, with its end caps and cut sides plain. Materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`, `a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side`, `a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn`, `export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format`, `a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side`. @@ -1723,6 +1732,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. + Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way around. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is smoothed along its length (by up to 5% of its longer side, so a shaky line comes out as one curve at Auto-Smooth) and refitted with curves within 0.1% (level 0) to 2.5% (level 100) of it, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. With anchor points of a path direct-selected, only the section between them is smoothed. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests/devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. @@ -2102,6 +2112,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A marquee across those shapes selects the instance too, and a marquee across the shape an image's own fill or stroke paints outside its frame selects the image, except in outline mode. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`, `a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_marquee_on_the_shape_of_an_image_fill_selects_it`). Before, Pathfinder dropped those effects, and clicks and marquees took only the instance's bounds. + Direct Selection on a dynamic symbol's instance picks an object of the art where the geometry effects of the instance's fill and stroke draw it, not where the object's own shape no longer paints, and outlines it there. An instance nested in the art is picked and outlined where its reshaped art is drawn, and type with a fill or stroke of its own where its reshaped glyphs are drawn, not anywhere in their bounds; Type Object Selection by Path Only still picks type by its type path. An image is outlined where its own fills and strokes paint as well as by its frame. A clipping path is still picked and outlined by its own geometry. Outline view and layers with Preview off still take the plain shapes, and blends, envelopes and repeats in the art are picked without those effects. These are VectorCraft's own rules (engine `dynamic_symbols::direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it`, `a_picked_clipping_path_is_outlined_by_its_own_geometry`). Before, a part was picked and outlined at its plain shape only. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no ``, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`). EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it). @@ -2241,7 +2252,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). 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`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols 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 symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). @@ -2323,9 +2334,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, merging a layer that uses a Knockout option with the layers below it, 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), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) 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 converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, 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), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) 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 with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`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` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.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` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group and leaves a clipping mask released, edited or made in the document as it is, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.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`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). @@ -2374,7 +2386,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - In the Separations Preview panel, an Alt-click (Option-click on macOS) on the eye of the plate shown alone shows every plate again, spot plates included, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for a second modified click on the eye (`view.separationsPreview {soloToggle: plate}`); an Alt-click on a plate shown among others shows only that plate, as the help page describes for the first one. VectorCraft's own rules: an Alt-click on a hidden plate, on another plate while one shows alone or while no plate is shown shows only that plate, and `only` still shows just the named plate when repeated (`crates/engine/src/tests/colormgmt.rs`, `crates/ui-egui/src/panels/separations.rs`). - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. - - On a PostScript plate, an overprinting gradient that puts the plate's ink down in some places and none in others leaves the ink below where it puts none: the stretches between stops of paper white and the padding past an end that is painted paper white (with the end stop's color at Level 2 and the color of the stretch next to it in a Level 3 smooth shading, which differ when two stops share the end's offset) are clipped out of a linear, radial or diamond gradient, the wedges of paper white out of a conic one, and the cells of paper white out of a freeform one (masked at Level 3, clipped at Level 2). This holds for fills, strokes and characters, and on spot plates. Where the gradient puts ink down, its amount replaces the ink below as before. A stop or point with up to half a percent of another ink in a color that counts as black puts none down, as a solid fill of that color does. PDF plates are unchanged. These are VectorCraft's own rules. Evidence: `print::tests::an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate`, `print::tests::an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate` and `print::tests::overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates` (`vectorcraft-eps`), `tests::print::a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates`. + - On a PostScript plate, an overprinting gradient that puts the plate's ink down in some places and none in others leaves the ink below where it puts none: the stretches between stops of paper white and the padding past an end that is painted paper white (with the end stop's color at Level 2 and the color of the stretch next to it in a Level 3 smooth shading, which differ when two stops share the end's offset) are clipped out of a linear, radial or diamond gradient, the wedges of paper white out of a conic one, and the cells whose 8-bit samples carry none of the plate's ink out of a freeform one (masked at Level 3, clipped at Level 2). This holds for fills, strokes and characters, and on spot plates. Where the gradient puts ink down, its amount replaces the ink below as before. A stop or point with up to half a percent of another ink in a color that counts as black puts none down, as a solid fill of that color does. PDF plates are unchanged. These are VectorCraft's own rules. Evidence: `print::tests::an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate`, `print::tests::an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate`, `print::tests::overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates` and `print::tests::an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_without_ink_on_a_postscript_plate` (`vectorcraft-eps`), `tests::print::a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates`. - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. A black linked to a swatch the document lacks separates from its own values, so on PostScript plates it counts as an unlinked black (VectorCraft's own rule). Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates`, `print::overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root ``. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). diff --git a/docs/three-d.md b/docs/three-d.md index 2327eb1c24..4286c88f3e 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -689,15 +689,18 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. meet, again on the merged outline, which can have more points (bars crossing in a grid trace every hole between them); past it, the shape is too complex for the effect. - The faces drawn, exported and made by **Object › Expand Appearance** keep the shape's curves: the caps of - Extrude & Bevel, the flat face of Rotate, and the edges of the walls and bevels where they meet a cap are cubic - curves, with smooth anchors where the art's are smooth, while visibility and depth are worked out on the - sampled points. Without perspective and bevel each curve maps exactly. With perspective, a curve is split into - cubics until each lies within 0.001 pt of the projected outline. A face inset or outset by a bevel follows its - sampled outline within the sampling tolerance above, one curve for each sampled edge through its two sampled - points, so the cap and the walls next to it draw the edge they share as the same curves. The edges between two bevel steps or two wall slices, a - piece of curve that does not fit after 8 halvings, an edge of a twisted wall cut into pieces, and the curves - past 1,048,576 for one solid stay straight. The tolerances and limits are VectorCraft's own values. Inflate's - faces are polygons. + Extrude & Bevel, the flat face of Rotate, and every edge of the walls and bevels along the art's curves (at a + cap, between two bevel steps and between two wall slices) are cubic curves, with smooth anchors where the + art's are smooth, while visibility and depth are worked out on the sampled points. Without perspective and + bevel each curve maps exactly. With perspective, a curve is split into cubics until each lies within 0.001 pt + of the projected outline. A face inset or outset by a bevel follows its sampled outline within the sampling + tolerance above, one curve for each sampled edge through its two sampled points, so two faces that meet draw + the edge they share as the same curves. A twist cuts a wall's edge into pieces at points of the art's curve, + so each piece follows the same curve as the cap it meets. Inflate keeps the curves of its flat back, of its + side walls and of its front and puffed back where they meet the outline, within the sampling tolerance there; + the inside of a puffed surface stays flat facets. A piece of curve that does not fit after 8 halvings, the + curves past 1,048,576 for one solid, and the cells' edges left once Inflate has looked at 4,194,304 edges of + the outline to find them, stay straight. The tolerances and limits are VectorCraft's own values. - Inflate also limits the work of filling its grid, which grows with the outline's points times the grid cells its outline crosses. An outline of tens of thousands of points that crosses nearly every cell (a comb of 4,000 teeth across the shape) is refused because the 3D surface is too complex; a closed path of 65,536 points round a diff --git a/docs/type-parity.md b/docs/type-parity.md index 868b944bcd..94993affe1 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | diff --git a/xtask/src/test262.rs b/xtask/src/test262.rs index dfed1d8ae3..7ee456a6c2 100644 --- a/xtask/src/test262.rs +++ b/xtask/src/test262.rs @@ -4,7 +4,9 @@ //! runs `vectorcraft-js`'s `test262` tests, which parse the ES5 parse subset, run the ES5 //! `test/language` tests and the tests of the ES5 built-ins under `test/built-ins` and //! `test/annexB/built-ins` that need only the interpreter's built-ins, run the `test/built-ins` -//! tests for `String`, `Number`, `RegExp` and `Date`, and print each one's counts. +//! tests for `String`, `Number`, `RegExp` and `Date`, parse and run the `test/annexB/language` +//! tests and run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and +//! `Function`), and print each one's counts. //! //! It also fetches `json2.js`, Douglas Crockford's public-domain JSON polyfill //! (https://github.com/douglascrockford/JSON-js), at a pinned commit, checks it against its SHA-256