diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 06a62cb171..f953deda71 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -10,8 +10,9 @@ use super::{Node, PathData}; pub struct NodeExtras { /// Opacity mask (Transparency panel). Its art lives here, outside the layer tree. pub mask: Option>, - /// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows - /// them; `view` is its [`crate::TraceView`] id, absent for the tracing result). + /// Image Trace object: `{preset, params, view?, split?}` it was traced with (the Image Trace + /// panel shows them; `view` is its [`crate::TraceView`] id, absent for the tracing result, and + /// `split` the Split view's divider, [`crate::TraceView::split_of`]). pub trace: Option>, /// Object → Text Wrap: area type below this object (in the same layer) flows around it. pub wrap: Option, diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index 042d6b3ada..a2d17cc990 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -20,11 +20,18 @@ pub enum TraceView { OutlinesWithSource, /// Only the source image. Source, + /// The source image on the part of the image left of a divider across it, and the traced + /// shapes everywhere else ([`TraceView::split_of`]). + Split, } +/// Where the Split view's divider is when the `trace` settings name no valid position: across the +/// middle of the source image. +pub const DEFAULT_TRACE_SPLIT: f64 = 0.5; + impl TraceView { /// Panel order. - pub const ALL: [Self; 5] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source]; + pub const ALL: [Self; 6] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source, Self::Split]; /// The id used in command params and in the saved `trace` object. pub fn id(self) -> &'static str { @@ -34,6 +41,7 @@ impl TraceView { Self::Outlines => "outlines", Self::OutlinesWithSource => "outlinesWithSourceImage", Self::Source => "sourceImage", + Self::Split => "split", } } @@ -48,14 +56,21 @@ impl TraceView { trace.get("view").and_then(serde_json::Value::as_str).and_then(Self::from_id).unwrap_or_default() } - /// Whether the source image shows. - pub fn shows_source(self) -> bool { - matches!(self, Self::OutlinesWithSource | Self::Source) + /// The Split view's divider in `trace` settings: the fraction of the source image's width, from + /// its left edge in its own pixels, that shows the source image ([`DEFAULT_TRACE_SPLIT`] when + /// `split` is missing, not a number or outside 0 to 1). + pub fn split_of(trace: &serde_json::Value) -> f64 { + trace.get("split").and_then(serde_json::Value::as_f64).filter(|f| (0.0..=1.0).contains(f)).unwrap_or(DEFAULT_TRACE_SPLIT) } - /// Whether the traced shapes show filled. + /// Whether the source image shows (in the Split view, on one side of the divider). + pub fn shows_source(self) -> bool { + matches!(self, Self::OutlinesWithSource | Self::Source | Self::Split) + } + + /// Whether the traced shapes show filled (in the Split view, on one side of the divider). pub fn shows_result(self) -> bool { - matches!(self, Self::Result | Self::ResultWithOutlines) + matches!(self, Self::Result | Self::ResultWithOutlines | Self::Split) } /// Whether the traced shapes' outlines show. @@ -69,6 +84,12 @@ impl Node { pub fn trace_view(&self) -> TraceView { self.extras().trace.as_deref().map(TraceView::of).unwrap_or_default() } + + /// The Split view's divider of an Image Trace object ([`TraceView::split_of`]; + /// [`DEFAULT_TRACE_SPLIT`] for anything else). + pub fn trace_split(&self) -> f64 { + self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of) + } } #[cfg(test)] @@ -89,6 +110,26 @@ mod tests { g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "sepia"}))); assert_eq!(g.trace_view(), TraceView::Result); } + + #[test] + fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() { + let mut g = Node::group(crate::NodeId(1), vec![]); + assert_eq!(g.trace_split(), DEFAULT_TRACE_SPLIT); + assert_eq!(TraceView::from_id("Split"), Some(TraceView::Split)); + assert!(TraceView::Split.shows_source() && TraceView::Split.shows_result() && !TraceView::Split.shows_outlines()); + for (split, want) in [ + (serde_json::json!(0.25), 0.25), + (serde_json::json!(0), 0.0), + (serde_json::json!(1), 1.0), + (serde_json::json!(-0.1), DEFAULT_TRACE_SPLIT), + (serde_json::json!(1.5), DEFAULT_TRACE_SPLIT), + (serde_json::json!("0.3"), DEFAULT_TRACE_SPLIT), + (serde_json::Value::Null, DEFAULT_TRACE_SPLIT), + ] { + g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split}))); + assert_eq!(g.trace_split(), want, "{split}"); + } + } #[test] fn live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle() { use crate::{Appearance, Document, ImageObject, NodeId, NodeKind}; @@ -132,6 +173,13 @@ mod tests { } } } + // The Split view measures the whole image wherever the divider is, so the selection box + // stays put while the divider moves. + for split in [0.0, 0.01, 1.0] { + let want = Rect::new(0.0, 0.0, 200.0, 200.0); + group.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split}))); + assert_eq!((group.geometric_bounds(), group.visual_bounds()), (Some(want), Some(want)), "split {split}"); + } group.extras_mut().trace = None; assert_eq!( group.geometric_bounds(), diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index b739ca5f7e..904e80df61 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -145,7 +145,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult; the Split view keeps the traced object's divider, else 0.5, and imageTrace.setView sets it), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), @@ -181,7 +181,7 @@ pub fn specs() -> Vec { "Image Trace View", [], None, - "{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"} how they draw on screen; exports, printing and Expand keep the tracing result → {ids, view}", + "{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"|\"split\" (the source image on the part of the image left of a divider across it, and the tracing result everywhere else), split?: 0-1 (the divider: the fraction of the source image's width, from its left edge, that shows the image; kept as it was when omitted, 0.5 for a new one)} how they draw on screen; exports, printing and Expand keep the tracing result, and tracing again keeps the view and the divider → {ids, view, split (view split: the first object's divider)}", has_selection_or_ids, trace_set_view ), diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 203fd62338..90c505cfb6 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -58,6 +58,12 @@ fn view_param(cmd: &str, p: &Value) -> Result> { v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids()))) } +/// The `split` param (the Split view's divider, 0 to 1), if given. +fn split_param(cmd: &str, p: &Value) -> Result> { + let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) }; + v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1")) +} + /// A saved Image Trace preset ([`crate::Prefs::trace_presets`]): a name and its settings. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -1026,9 +1032,14 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result> { pub(super) fn trace_set_view(s: &mut Session, p: &Value) -> Result { const C: &str = "imageTrace.setView"; let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?; + let split = split_param(C, p)?; let targets = trace_targets(s, p)?; let d = &s.doc()?.doc; - if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) { - return Ok(json!({ "ids": ids_json(&targets), "view": view.id() })); + let result = |d: &vectorcraft_doc::Document| { + let mut r = json!({ "ids": ids_json(&targets), "view": view.id() }); + if view == TraceView::Split + && let Some(n) = targets.first().and_then(|g| d.node(*g)) + { + r["split"] = json!(split.unwrap_or_else(|| n.trace_split())); + } + r + }; + if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view && split.is_none_or(|f| n.trace_split() == f))) { + return Ok(result(d)); } s.edit("Image Trace View", |d, _| { for g in &targets { let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; + if n.extras_if_any().and_then(|e| e.trace.as_deref()).is_none_or(|t| !t.is_object()) { + n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom" }))); + } if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) { t.insert("view".into(), json!(view.id())); - } else { - n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() }))); + if let Some(f) = split { + t.insert("split".into(), json!(f)); + } } } Ok(()) })?; - Ok(json!({ "ids": ids_json(&targets), "view": view.id() })) + Ok(result(&s.doc()?.doc)) } pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 33483c5e21..8296619f91 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -8617,6 +8617,54 @@ fn image_trace_view_is_stored_kept_and_validated() { assert!(s.execute("imageTrace.setView", &json!({"id": a.0, "view": "outlines"})).is_err()); } +/// The Split view's divider is set with the view, kept when omitted, when tracing again and through +/// save and open, adds no undo step when unchanged and one when changed, and is checked. On screen +/// the source image shows left of it and the result right of it; exports draw the result. +#[test] +fn image_trace_split_view_keeps_and_validates_its_divider() { + let mut s = session(); + let g = disc_on_blue(&mut s); + // The image covers 50 to 250 across; the disc 90 to 210, so the divider moves over the disc. + let r = s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap(); + assert_eq!((r["view"].as_str(), r["split"].as_f64()), (Some("split"), Some(0.5))); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("imageTrace.setView", &json!({"view": "split", "split": 0.25})).unwrap(); + assert_eq!(r["split"].as_f64(), Some(0.25)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(node(&s, g).trace_split(), 0.25); + for same in [json!({"view": "split", "split": 0.25}), json!({"view": "split"})] { + let r = s.execute("imageTrace.setView", &same).unwrap(); + assert_eq!(r["split"].as_f64(), Some(0.25), "{same}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{same}: no undo step"); + } + // Pixels at y = 60 (above the disc): the image's blue left of x = 100, white right of it. + let blue = |p: [u8; 4]| p[0] < 200 && p[2] > 245; + let white = |p: [u8; 4]| p[0] > 245 && p[1] > 245 && p[2] > 245; + let screen = render_doc(&s, true); + assert!(blue(screen.pixel(60, 60)) && blue(screen.pixel(95, 60)), "{:?}", screen.pixel(95, 60)); + assert!(white(screen.pixel(105, 60)) && white(screen.pixel(240, 60)), "{:?}", screen.pixel(105, 60)); + let export = render_doc(&s, false); + assert!(white(export.pixel(60, 60)), "exports draw the tracing result"); + // Another view keeps the divider for when Split is chosen again. + s.execute("imageTrace.setView", &json!({"view": "outlines"})).unwrap(); + assert_eq!(node(&s, g).trace_split(), 0.25); + s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap(); + let g = NodeId(s.execute("imageTrace.make", &json!({"id": g.0, "params": {"ignoreWhite": true, "noise": 30}})).unwrap()["id"].as_u64().unwrap()); + assert_eq!((node(&s, g).trace_view(), node(&s, g).trace_split()), (vectorcraft_doc::TraceView::Split, 0.25), "tracing again"); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25)); + // Bad dividers are refused and change nothing. + let steps = s.doc().unwrap().history.undo.len(); + for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] { + assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}"); + } + assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25)); + for edge in [0.0, 1.0] { + s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap(); + assert_eq!(node(&s, g).trace_split(), edge); + } +} + #[test] fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { let mut s = session(); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index bd26c851cd..3e79641a51 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -499,7 +499,7 @@ impl Renderer { fn draw_content(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, knockout: bool) { match &n.kind { NodeKind::Group { children, clip: false } if f.opts.trace_views && !f.opts.outline && Self::trace_view(f, n) != TraceView::Result => { - self.draw_trace_view(ctx, f, children, Self::trace_view(f, n), knockout) + self.draw_trace_view(ctx, f, children, (Self::trace_view(f, n), n.trace_split()), knockout) } NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { self.draw_children(ctx, f, children, knockout) @@ -641,9 +641,56 @@ impl Renderer { } /// An Image Trace object's `children` (the hidden source image, then the traced shapes) as - /// `view` shows them on screen. - fn draw_trace_view(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc], view: TraceView, knockout: bool) { + /// `view` shows them on screen, with `split`, the Split view's divider + /// ([`TraceView::split_of`]). + fn draw_trace_view(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc], (view, split): (TraceView, f64), knockout: bool) { let Some((source, shapes)) = children.split_first() else { return }; + if view == TraceView::Split { + // Each side is drawn once under a plain clip (no layer and no second render), in the + // image's own pixels so the divider turns with the image: the source image on the part + // of the image left of the divider, and the traced shapes everywhere else, art past any + // of the image's edges included. Without an image, with one of no size or that can't + // be inverted, or with the divider at the image's left edge, the traced shapes draw as + // they are. + let NodeKind::Image(im) = &source.kind else { return self.draw_children(ctx, f, shapes, knockout) }; + let (w, h) = (f64::from(im.width), f64::from(im.height)); + let at = w * split.clamp(0.0, 1.0); + let det = im.xf.determinant(); + if w <= 0.0 || h <= 0.0 || at <= 0.0 || !det.is_finite() || det.abs() < 1e-12 { + return self.draw_children(ctx, f, shapes, knockout); + } + // The result's side covers the image and the traced shapes' cached bounds, two screen + // pixels more so anti-aliased edges are not cut, in the image's pixels, less the + // source's side. + let inverse = im.xf.inverse(); + let (mut x0, mut x1, mut y0, mut y1) = (0.0_f64, w, 0.0_f64, h); + for c in shapes { + if let Some(b) = self.bounds_of(f.symbols, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) { + for q in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] { + let p = inverse * kurbo::Point::new(q.0, q.1); + if p.x.is_finite() && p.y.is_finite() { + (x0, x1, y0, y1) = (x0.min(p.x), x1.max(p.x), y0.min(p.y), y1.max(p.y)); + } + } + } + } + let part = |p: &mut BezPath, x0: f64, x1: f64, y0: f64, y1: f64| { + p.move_to(im.xf * kurbo::Point::new(x0, y0)); + p.line_to(im.xf * kurbo::Point::new(x1, y0)); + p.line_to(im.xf * kurbo::Point::new(x1, y1)); + p.line_to(im.xf * kurbo::Point::new(x0, y1)); + p.close_path(); + }; + let (mut left, mut right) = (BezPath::new(), BezPath::new()); + part(&mut left, 0.0, at, 0.0, h); + part(&mut right, x0, x1, y0, y1); + part(&mut right, 0.0, at, 0.0, h); + let comp = Composite { clip: Some((&left, FillRule::NonZero)), blends: true, ..Default::default() }; + self.group(ctx, f, comp, &mut |r, c, fr| r.draw_forced_arc(c, fr, source)); + let comp = Composite { clip: Some((&right, FillRule::EvenOdd)), blends: true, ..Default::default() }; + self.group(ctx, f, comp, &mut |r, c, fr| r.draw_children(c, fr, shapes, knockout)); + return; + } if view.shows_source() && matches!(source.kind, NodeKind::Image(_)) { self.draw_forced_arc(ctx, f, source); } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 2a0e6c9a93..d3c9b708d5 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -841,6 +841,79 @@ fn trace_source_applies_the_hidden_image_mask() { assert_eq!(img.pixel(70, 50), [255, 255, 255, 255]); } +/// The Split view draws the source image left of its divider and the traced shapes right of it, +/// along the image's own width (also when the image is turned), with traced art past any of the +/// image's edges drawn whatever the divider, in the same frames a renderer that keeps its caches +/// draws, and in a zoomed and scrolled view and a turned view; exports draw the tracing result. +#[test] +fn split_view_draws_the_source_on_one_side_of_the_divider_and_the_result_on_the_other() { + use vectorcraft_doc::{ImageBlob, ImageObject}; + let mut png = vec![]; + image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let red = |p: [u8; 4]| p[0] > 200 && p[1] < 60 && p[2] < 60; + let blue = |p: [u8; 4]| p[2] > 200 && p[0] < 60; + // A red 80 × 80 source image at 10, 10, turned a half turn about its center when `turned`, with + // a blue traced square over all of it. + for turned in [false, true] { + let mut d = Document::new(100.0, 100.0); + d.images.insert("red".into(), ImageBlob::new("image/png", png.clone())); + let turn = if turned { Affine::rotate_about(std::f64::consts::PI, kurbo::Point::new(50.0, 50.0)) } else { Affine::IDENTITY }; + let xf = turn * Affine::translate((10.0, 10.0)) * Affine::scale(80.0); + let im = ImageObject { key: "red".into(), width: 1, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + let mut source = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + source.visible = false; + let shape = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + // Traced art past the image's right edge on the page (a stroke along it, say). + let past = rect_node(&mut d, Rect::new(92.0, 46.0, 98.0, 54.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + // And above the image's top edge, near its left edge. + let above = rect_node(&mut d, Rect::new(14.0, 2.0, 26.0, 8.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + let mut g = Node::group(d.alloc_id(), vec![Arc::new(source), Arc::new(shape), Arc::new(past), Arc::new(above)]); + let id = g.id; + g.extras_mut().trace = Some(Box::new(serde_json::json!({ "view": "split", "split": 0.25 }))); + d.insert(Some(d.layers[0].id), 0, g).unwrap(); + let screen = RenderOptions { trace_views: true, background: Some([255; 4]), ..Default::default() }; + let export = RenderOptions { background: Some([255; 4]), ..Default::default() }; + let mut kept = Renderer::new(); + for split in [0.25, 0.0, 1.0, 0.25] { + if let Some(n) = d.node_mut(id) { + n.extras_mut().trace = Some(Box::new(serde_json::json!({ "view": "split", "split": split }))); + } + // The divider in page space: 30 across from the image's left edge, or from its right + // edge on the page once the image is turned. + let at = if turned { 90.0 - 80.0 * split } else { 10.0 + 80.0 * split }; + // The view: as is, zoomed in twice and scrolled, and turned a half turn about the page's + // middle; `px` finds the pixel showing page point (x, y). + let views: [(Affine, u32); 3] = [ + (Affine::IDENTITY, 100), + (Affine::translate((5.0, 7.0)) * Affine::scale(2.0), 210), + (Affine::rotate_about(std::f64::consts::PI, kurbo::Point::new(50.0, 50.0)), 100), + ]; + for (view, size) in views { + let px = |r: &Rendered, x: f64, y: f64| { + let q = view * kurbo::Point::new(x, y); + r.pixel(q.x.floor() as u32, q.y.floor() as u32) + }; + for r in [kept.render(&d, size, size, view, &screen), Renderer::new().render(&d, size, size, view, &screen)] { + for x in [12.5, 30.5, 48.5, 52.5, 70.5, 88.5] { + let p = px(&r, x, 50.5); + let source = if turned { x > at } else { x < at }; + assert!(if source { red(p) } else { blue(p) }, "turned {turned}, split {split}, view {view:?}, x = {x}: {p:?}"); + } + assert_eq!(px(&r, 5.5, 50.5), [255; 4], "nothing outside the image"); + // The art past the image's edges shows on either side of the divider. + let green = |p: [u8; 4]| p[1] > 200 && p[0] < 60 && p[2] < 60; + for (x, y) in [(95.5, 50.5), (20.5, 5.5)] { + let p = px(&r, x, y); + assert!(green(p), "turned {turned}, split {split}, view {view:?}, ({x}, {y}): {p:?}"); + } + } + } + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &export); + assert!([12u32, 50, 88].iter().all(|x| blue(r.pixel(*x, 50))), "exports draw the result"); + } + } +} + #[test] fn artboards_white_on_pasteboard() { let d = Document::new(50.0, 50.0); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 0b7bef755f..486fc5804b 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -47,6 +47,7 @@ pub mod slice; pub mod symbolism; pub mod text; pub mod touchtype; +pub mod trace_split; pub mod typewidget; pub mod xform; diff --git a/crates/tools/src/mirror.rs b/crates/tools/src/mirror.rs index 5560fbc321..31253003d9 100644 --- a/crates/tools/src/mirror.rs +++ b/crates/tools/src/mirror.rs @@ -184,4 +184,29 @@ mod tests { spec.kind = RepeatKind::Mirror { angle: f64::NAN, center: Point::ZERO }; assert!(MirrorAxis::of(&doc, &selection, 1.0).is_none()); } + + #[test] + fn a_tool_switch_cancels_a_mirror_axis_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (mut doc, id) = doc_with_rect(); + let mut source = doc.node(id).unwrap().clone(); + source.id = doc.alloc_id(); + doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::mirror(vec![Arc::new(source)], 90.0, 10.0)); + let mut selection = Selection::default(); + selection.set([id]); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let axis = MirrorAxis::of(&doc, &selection, c.zoom).unwrap(); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, axis.center.x, axis.center.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, axis.center.x + 20.0, axis.center.y)); + assert!(matches!(a.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not moved the axis leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, axis.center.x, axis.center.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/repeat_grid.rs b/crates/tools/src/repeat_grid.rs index 07187a6a5a..eecc6ba0fe 100644 --- a/crates/tools/src/repeat_grid.rs +++ b/crates/tools/src/repeat_grid.rs @@ -392,4 +392,24 @@ mod tests { assert_eq!(cursor(&c, g.rows_at), Some(Cursor::ResizeV)); assert_eq!(cursor(&c, g.corner_at), Some(Cursor::ResizeNwSe)); } + + #[test] + fn a_tool_switch_cancels_a_grid_handle_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (doc, selection) = grid(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, g.rows_at.x, g.rows_at.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, g.rows_at.x, g.rows_at.y + 150.0)); + assert!(preview(&a).is_some(), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not changed the grid leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, g.rows_at.x, g.rows_at.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs index 42a9f4395f..7304570404 100644 --- a/crates/tools/src/repeat_radial.rs +++ b/crates/tools/src/repeat_radial.rs @@ -681,4 +681,26 @@ mod tests { assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 32.0))), Some(&json!({"instances": 9}))); assert!(matches!(d.finish().as_slice(), [Action::Commit])); } + + #[test] + fn a_tool_switch_cancels_a_radial_handle_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (doc, selection) = radial(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + let out = (h.radius_at - h.center) / 100.0; + let to = h.radius_at + out * 25.0; + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, h.radius_at.x, h.radius_at.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert_eq!(preview(&a), Some(&json!({"radius": 125.0})), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not changed the repeat leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, h.radius_at.x, h.radius_at.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e9c3e2bb03..b0802595a1 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -153,6 +153,8 @@ enum State { GridRepeat(crate::repeat_grid::GridDrag), /// Drag a radial repeat's instances or radius handle. RadialRepeat(crate::repeat_radial::RadialDrag), + /// Drag the divider of an Image Trace object in the Split view. + TraceSplit(crate::trace_split::SplitDrag), /// Dragging a bracket of type on a path. Bracket(BracketDrag), /// Dragging a 9-slice guide of the symbol being edited. @@ -831,7 +833,7 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or /// rotation, a marquee, a corner widget, a pie widget, a polygon's side widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror - /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy + /// axis, a grid repeat's handles, an Image Trace divider, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { @@ -905,14 +907,19 @@ impl Tool for SelectionTool { out } - /// Switching tools during a drag of a blend widget, a corner widget, a pie widget or a - /// polygon's side widget cancels it, as Escape does: its value goes back. + /// Switching tools during a drag of a blend widget, a corner widget, a pie widget, a + /// polygon's side widget, a mirror axis, a grid or radial repeat's handles or an Image Trace + /// divider cancels it, as Escape does: its value goes back. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { match std::mem::take(&mut self.state) { State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel], State::Corner(c) if c.adjusting() => vec![Action::Cancel], State::Pie(d) if d.adjusting() => vec![Action::Cancel], State::Sides(d) => d.cancel(), + State::Mirror(d) => d.cancel(), + State::GridRepeat(d) => d.cancel(), + State::RadialRepeat(d) => d.cancel(), + State::TraceSplit(d) => d.cancel(), State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![], other => { self.state = other; @@ -926,7 +933,9 @@ impl Tool for SelectionTool { State::Marquee { .. } => key == ToolKey::Letter('e'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right), - State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, + State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::TraceSplit(_) | State::NineSlice(_) => { + key == ToolKey::Escape + } _ => false, } } @@ -970,6 +979,7 @@ impl Tool for SelectionTool { State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), State::RadialRepeat(d) => d.adjusting(), + State::TraceSplit(d) => d.adjusting(), _ => false, } } @@ -1296,6 +1306,9 @@ impl Tool for SelectionTool { if let State::RadialRepeat(d) = &self.state { return d.cursor(cx); } + if let State::TraceSplit(d) = &self.state { + return d.cursor(cx); + } if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) { return Cursor::Move; } @@ -1303,8 +1316,10 @@ impl Tool for SelectionTool { && !m.cmd && !m.ctrl && !m.alt - && let Some(cursor) = - crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)).or_else(|| crate::repeat_radial::cursor(cx, p)) + && let Some(cursor) = crate::mirror::cursor(cx, p) + .or_else(|| crate::repeat_grid::cursor(cx, p)) + .or_else(|| crate::repeat_radial::cursor(cx, p)) + .or_else(|| crate::trace_split::cursor(cx, p)) { return cursor; } @@ -1668,6 +1683,21 @@ impl SelectionTool { _ => return Some(vec![]), } } + if let State::TraceSplit(mut d) = self.state.clone() { + match ev.kind { + PointerKind::Drag | PointerKind::Up => { + let mut out = d.drag(cx, ev.pos); + if ev.kind == PointerKind::Up { + out.extend(d.finish()); + self.state = State::Idle; + } else { + self.state = State::TraceSplit(d); + } + return Some(out); + } + _ => return Some(vec![]), + } + } if matches!(self.state, State::Idle) && ev.kind == PointerKind::Down && let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods) @@ -1692,6 +1722,14 @@ impl SelectionTool { self.hover = None; return Some(vec![]); } + if matches!(self.state, State::Idle) + && ev.kind == PointerKind::Down + && let Some(d) = crate::trace_split::SplitDrag::hit(cx, ev.pos, ev.mods) + { + self.state = State::TraceSplit(d); + self.hover = None; + return Some(vec![]); + } None } diff --git a/crates/tools/src/trace_split.rs b/crates/tools/src/trace_split.rs new file mode 100644 index 0000000000..f5949be2a4 --- /dev/null +++ b/crates/tools/src/trace_split.rs @@ -0,0 +1,284 @@ +//! The divider of an Image Trace object in the Split view: the source image shows on its left +//! (in the image's own pixels) and the tracing result on its right. Drawing and hit testing share +//! the document-space geometry here; a drag previews `imageTrace.setView` and commits it as one +//! undo step. +use serde_json::json; +use vectorcraft_doc::{Document, NodeId, NodeKind, Selection, TraceView}; +use vectorcraft_geom::{Affine, Point}; + +use crate::{Action, Cursor, Mods, ToolContext}; + +/// How near (screen points) the pointer must come to the divider to take it. +pub const HIT_PX: f64 = 5.0; + +/// The divider's half length past each end of its grip, in screen points. +pub const GRIP_HALF: f32 = 10.0; + +/// The Split view's divider of one selected Image Trace object, in document space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TraceDivider { + /// The Image Trace object. + pub id: NodeId, + /// The fraction of the source image's width, from its left edge, that shows the image. + pub split: f64, + /// Where the divider meets the image's top and bottom edges. + pub ends: [Point; 2], + /// The source image's pixel-to-document transform. + xf: Affine, + width: f64, +} + +impl TraceDivider { + /// The divider of the one Image Trace object selected whole, when it shows the Split view. + pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { + let [id] = selection.objects.as_slice() else { return None }; + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let n = doc.node(*id)?; + if n.extras().trace.is_none() || n.trace_view() != TraceView::Split { + return None; + } + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + let NodeKind::Image(im) = &children.first()?.kind else { return None }; + let (width, height) = (f64::from(im.width), f64::from(im.height)); + let det = im.xf.determinant(); + if width <= 0.0 || height <= 0.0 || !det.is_finite() || det.abs() < 1e-12 || !im.xf.as_coeffs().iter().all(|c| c.is_finite()) { + return None; + } + let split = n.trace_split(); + let at = width * split; + let ends = [im.xf * Point::new(at, 0.0), im.xf * Point::new(at, height)]; + ends.iter().all(|p| finite(*p)).then_some(Self { id: *id, split, ends, xf: im.xf, width }) + } + + /// The divider position for document point `p`: the fraction of the image's width left of + /// it, from 0 to 1, rounded to a ten-thousandth. + pub fn split_at(&self, p: Point) -> Option { + let local = self.xf.inverse() * p; + let f = (local.x / self.width).clamp(0.0, 1.0); + f.is_finite().then(|| (f * 10_000.0).round() / 10_000.0) + } + + /// How far the image's left-to-right direction is turned (counter-clockwise degrees on the + /// page), for the resize cursor. + fn angle(&self) -> f64 { + let across = self.xf * Point::new(1.0, 0.0) - self.xf * Point::ZERO; + (-across.y).atan2(across.x).to_degrees() + } + + /// The divider under document point `p`. Nothing with the bounding box hidden or in Outline + /// mode, where the canvas draws neither the divider nor the split. + fn hit(cx: &ToolContext, p: Point) -> Option { + if !cx.show_bbox || cx.outline || !finite(p) { + return None; + } + let d = Self::of(cx.doc, cx.selection, cx.zoom)?; + let [a, b] = d.ends; + let v = b - a; + let length = v.hypot(); + if !length.is_finite() || length <= 0.0 { + return None; + } + let unit = v / length; + let along = (p - a).dot(unit).clamp(0.0, length); + // A bounding-box handle or a shown center point under the pointer keeps its own drag. + ((a + unit * along).distance(p) <= cx.tol(HIT_PX) + && !crate::select::bbox_handle_at(cx, p) + && crate::select::hit_center(cx, p, cx.point_tol()).is_none()) + .then_some(d) + } +} + +fn finite(p: Point) -> bool { + p.x.is_finite() && p.y.is_finite() +} + +fn resize_cursor(d: &TraceDivider, cx: &ToolContext) -> Cursor { + crate::select::handle_cursor(crate::bbox::Handle::Right, d.angle() - cx.view_angle()) +} + +/// The resize cursor over the divider at `p`, turned with the image and the view. +pub fn cursor(cx: &ToolContext, p: Point) -> Option { + TraceDivider::hit(cx, p).map(|d| resize_cursor(&d, cx)) +} + +/// A drag of the divider: it previews `imageTrace.setView` while the pointer moves and commits +/// it as one undo step. +#[derive(Clone, Debug)] +pub struct SplitDrag { + divider: TraceDivider, + start: Point, + began: bool, +} + +impl SplitDrag { + pub fn hit(cx: &ToolContext, p: Point, mods: Mods) -> Option { + if mods.cmd || mods.ctrl || mods.alt { + return None; + } + let divider = TraceDivider::hit(cx, p)?; + Some(Self { divider, start: p, began: false }) + } + + pub fn adjusting(&self) -> bool { + self.began + } + + pub fn cursor(&self, cx: &ToolContext) -> Cursor { + resize_cursor(&self.divider, cx) + } + + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !finite(p) || (!self.began && p.distance(self.start) < cx.tol(3.0)) { + return vec![]; + } + let Some(split) = self.divider.split_at(p) else { return vec![] }; + let mut out = vec![]; + if !self.began { + self.began = true; + out.push(Action::Begin("Image Trace View".into())); + } + out.push(Action::Preview("imageTrace.setView".into(), json!({"id": self.divider.id.0, "view": TraceView::Split.id(), "split": split}))); + out + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + pub fn cancel(self) -> Vec { + if self.began { vec![Action::Cancel] } else { vec![] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::{cx, paint}; + use std::sync::Arc; + use vectorcraft_doc::{ImageObject, Node}; + + /// A document with an Image Trace object over a 100 × 50 image placed by `xf`, in `view`. + fn traced(xf: Affine, view: &str, split: f64) -> (Document, NodeId) { + let mut doc = Document::new(400.0, 400.0); + let im = ImageObject { key: "k".into(), width: 100, height: 50, xf, link: None, placement: Default::default(), pixels: None }; + let mut source = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + source.visible = false; + let mut g = Node::group(doc.alloc_id(), vec![Arc::new(source)]); + g.extras_mut().trace = Some(Box::new(json!({"view": view, "split": split}))); + let id = g.id; + let layer = doc.layers[0].id; + doc.insert(Some(layer), 0, g).unwrap(); + (doc, id) + } + + #[test] + fn the_divider_shows_only_for_one_selected_split_view_and_follows_the_image() { + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.25); + assert!(TraceDivider::of(&doc, &selection, 1.0).is_none(), "nothing selected"); + selection.set([id]); + let d = TraceDivider::of(&doc, &selection, 1.0).unwrap(); + assert_eq!((d.split, d.ends), (0.25, [Point::new(35.0, 20.0), Point::new(35.0, 70.0)])); + for zoom in [0.0, -1.0, f64::NAN] { + assert!(TraceDivider::of(&doc, &selection, zoom).is_none()); + } + let (other, id) = traced(Affine::IDENTITY, "sourceImage", 0.25); + selection.set([id]); + assert!(TraceDivider::of(&other, &selection, 1.0).is_none(), "another view"); + // A turned and scaled image: the divider runs along the image's own height. + let xf = Affine::translate((200.0, 100.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale(2.0); + let (doc, id) = traced(xf, "split", 0.5); + selection.set([id]); + let d = TraceDivider::of(&doc, &selection, 1.0).unwrap(); + assert!(d.ends[0].distance(Point::new(200.0, 200.0)) < 1e-9 && d.ends[1].distance(Point::new(100.0, 200.0)) < 1e-9, "{:?}", d.ends); + assert_eq!(d.split_at(Point::new(150.0, 150.0)), Some(0.25)); + assert_eq!(d.split_at(Point::new(150.0, 900.0)), Some(1.0), "clamped"); + let c = cx(&doc, &selection, &paint); + assert_eq!(cursor(&c, Point::new(150.0, 200.0)), Some(Cursor::ResizeV)); + assert_eq!(cursor(&c, Point::new(150.0, 210.0)), None, "past the hit distance"); + let mut c = cx(&doc, &selection, &paint); + c.show_bbox = false; + assert_eq!(cursor(&c, Point::new(150.0, 200.0)), None, "bounding box hidden"); + assert!(SplitDrag::hit(&c, Point::new(150.0, 200.0), Mods::default()).is_none(), "bounding box hidden"); + let mut c = cx(&doc, &selection, &paint); + c.outline = true; + assert!(SplitDrag::hit(&c, Point::new(150.0, 200.0), Mods::default()).is_none(), "Outline mode"); + } + + #[test] + fn dragging_the_divider_previews_the_view_and_commits_once() { + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + selection.set([id]); + for zoom in [0.5, 1.0, 4.0] { + let mut c = cx(&doc, &selection, &paint); + c.zoom = zoom; + let on = Point::new(60.0 + 4.0 / zoom, 40.0); + assert_eq!(cursor(&c, on), Some(Cursor::ResizeH), "zoom {zoom}"); + assert!(SplitDrag::hit(&c, Point::new(60.0 + 6.0 / zoom, 40.0), Mods::default()).is_none(), "zoom {zoom}"); + assert!(SplitDrag::hit(&c, on, Mods { alt: true, ..Default::default() }).is_none()); + let mut drag = SplitDrag::hit(&c, on, Mods::default()).unwrap(); + assert!(drag.drag(&c, on + vectorcraft_geom::Vec2::new(1.0 / zoom, 0.0)).is_empty(), "under the drag threshold"); + assert!(drag.drag(&c, Point::new(f64::NAN, 0.0)).is_empty()); + let out = drag.drag(&c, Point::new(85.0, 300.0)); + assert!( + matches!(&out[..], [Action::Begin(_), Action::Preview(id, p)] + if id == "imageTrace.setView" && p["split"] == json!(0.75) && p["view"] == "split"), + "{out:?}" + ); + let out = drag.drag(&c, Point::new(-50.0, 30.0)); + assert!(matches!(&out[..], [Action::Preview(_, p)] if p["split"] == json!(0.0)), "{out:?}"); + assert!(drag.adjusting()); + assert!(matches!(drag.clone().finish()[..], [Action::Commit])); + assert!(matches!(drag.cancel()[..], [Action::Cancel])); + } + } + + /// With Show Center on, a press on the center point where the divider crosses it moves the + /// object; the rest of the divider still takes a press. + #[test] + fn the_center_point_keeps_its_drag_on_the_divider() { + use vectorcraft_doc::{Appearance, LiveShape}; + let paint = paint(); + let mut selection = Selection::default(); + let (mut doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + let xf = Affine::translate((10.0, 20.0)); + let shape = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }; + let path = Node::path(doc.alloc_id(), shape.to_path(), Appearance::default_art()); + doc.insert(Some(id), 1, path).unwrap(); + doc.node_mut(id).unwrap().edit_attrs(|a| a.show_center = Some(true)); + selection.set([id]); + let c = cx(&doc, &selection, &paint); + assert_eq!(crate::select::hit_center(&c, Point::new(60.0, 45.0), c.point_tol()).map(|(i, _)| i), Some(id)); + assert_eq!(cursor(&c, Point::new(60.0, 45.0)), None, "the center point"); + assert!(SplitDrag::hit(&c, Point::new(60.0, 45.0), Mods::default()).is_none(), "the center point"); + assert_eq!(cursor(&c, Point::new(60.0, 33.0)), Some(Cursor::ResizeH)); + } + + /// Switching away from the Selection tool during a divider drag cancels it, as Escape does: + /// the view goes back. After a press that has not moved there is nothing to put back. + #[test] + fn a_tool_switch_cancels_a_divider_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + selection.set([id]); + let c = cx(&doc, &selection, &paint); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 60.0, 40.0)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 85.0, 40.0)); + assert!(matches!(a.first(), Some(Action::Begin(_))), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 85.0, 40.0)).is_empty()); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 60.0, 40.0)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 02833a7c09..9d85fbbd08 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -81,6 +81,7 @@ pub use tool_overlays::{HiddenChars, SpellingMarks}; use tool_overlays::{ grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, print_tiling_overlay, radial_repeat_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, + trace_split_overlay, }; pub(crate) use view::animated_zoom; pub(crate) use view::drag_rotation; @@ -1352,6 +1353,7 @@ fn selection_visuals( mirror_axis_overlay(app, painter, xf); grid_repeat_overlay(app, painter, xf); radial_repeat_overlay(app, painter, xf); + trace_split_overlay(app, painter, xf); if app.ui.view.text_threads { // Under the tools' overlays: a selected frame's own ports are drawn over its thread's. let mut threads = thread_overlays(app, xf.zoom); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8cc87bff47..a4bd86418b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4938,6 +4938,91 @@ fn mirror_axis_drag_uses_canvas_coordinates_in_a_zoomed_rotated_view() { } } +/// The Split view's divider of a selected Image Trace object is drawn where the Selection tool +/// takes it in a zoomed, turned view. Dragging its middle across the image previews the divider, +/// commits one undo step and leaves the traced art where it was; Undo puts the divider back. +#[test] +fn trace_split_divider_drag_in_a_zoomed_rotated_view_is_one_undo_step() { + use vectorcraft_tools::trace_split::TraceDivider; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let data = vectorcraft_format::base64_encode(&crate::tests_sysclip::blue_png()); + app.run("file.place", json!({"name": "blue.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap(); + app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); + app.run("imageTrace.setView", json!({"view": "split"})).unwrap(); + app.select_tool("selection"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let divider = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + TraceDivider::of(&st.doc, &st.selection, app.view().unwrap().zoom).unwrap() + }; + let initial = divider(&app); + assert_eq!(initial.split, 0.5); + let middle = initial.ends[0].midpoint(initial.ends[1]); + { + let v = app.view_mut().unwrap(); + (v.zoom, v.rotation, v.center, v.fitted) = (30.0, 30.0, middle, true); + } + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let art = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.node(initial.id).unwrap().geometric_bounds() + }; + let before = (art(&app), app.session.active().unwrap().history.undo.len()); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + // The divider is drawn between its ends on screen. + let ends = initial.ends.map(|q| xf.to_screen(q)); + let drawn = shapes(&mut app, &ctx); + assert!( + drawn.iter().any(|s| matches!(s, Shape::LineSegment { points, .. } + if points.iter().zip(ends).all(|(a, b)| a.distance(b) < 0.5) || points.iter().rev().zip(ends).all(|(a, b)| a.distance(b) < 0.5))), + "the divider is drawn from {:?} to {:?}", + ends[0], + ends[1] + ); + // A quarter of the image's width to the right, in the image's own direction. + let from = xf.to_screen(middle); + let st = app.session.active().unwrap(); + let NodeKind::Image(im) = &st.doc.node(initial.id).unwrap().children().unwrap()[0].kind else { panic!("no source image") }; + let to = xf.to_screen(im.xf * vectorcraft_geom::Point::new(f64::from(im.width) * 0.75, f64::from(im.height) * 0.5)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + assert!((divider(&app).split - 0.75).abs() < 0.01, "the divider previews during the drag: {}", divider(&app).split); + frame(&mut app, &ctx, vec![button(to, false)]); + assert!((divider(&app).split - 0.75).abs() < 0.01); + assert_eq!((art(&app), app.session.active().unwrap().history.undo.len()), (before.0, before.1 + 1), "one undo step, the art unmoved"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(divider(&app).split, 0.5); + // Escape during a drag puts the divider back with no undo step. + let steps = app.session.active().unwrap().history.undo.len(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + assert!((divider(&app).split - 0.75).abs() < 0.01); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events: vec![escape], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + show(&mut app, ui) + }); + out.textures_delta.clear(); + assert!(!app.session.tool_busy(), "Escape ends the drag"); + assert_eq!(divider(&app).split, 0.5, "Escape puts the divider back"); + frame(&mut app, &ctx, vec![button(to, false)]); + assert_eq!(divider(&app).split, 0.5, "Escape cancels the drag"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "no undo step"); + // With the bounding box hidden, the divider is not drawn. + app.ui.view.bounding_box = false; + let drawn = shapes(&mut app, &ctx); + assert!( + !drawn.iter().any(|s| matches!(s, Shape::LineSegment { points, .. } if points.iter().zip(ends).all(|(a, b)| a.distance(b) < 0.5))), + "no divider with the bounding box hidden" + ); +} + /// A selected grid repeat draws its row handle below the grid and a slider between its first /// two columns (none with the bounding box hidden). Dragging the row handle down two tiles in /// a zoomed view makes five rows without scaling the source, as one undo step, and the slider diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index bff6f174b9..958872d6b0 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -661,6 +661,35 @@ pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: & p.rect_stroke(handle, 2.0, Stroke::new(2.0, t.measure_bg), StrokeKind::Outside); } +/// The Split view's divider of the selected Image Trace object, where the Selection tool's hit +/// testing finds it: a line across the source image with a grip in its middle, at its place in the +/// zoomed, scrolled or turned view. Hidden with the bounding box and in Outline mode, as the hit +/// testing is. +pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { + if app.session.tool_id() != "selection" || !app.ui.view.bounding_box || app.outline_view() { + return; + } + let Some(st) = app.session.active() else { return }; + let Some(d) = vectorcraft_tools::trace_split::TraceDivider::of(&st.doc, &st.selection, xf.zoom) else { return }; + let ends = d.ends.map(|q| xf.to_screen(q)); + if !ends.iter().all(|q| q.is_finite()) { + return; + } + let t = Tokens::get(p.ctx()); + if let Some((a, b)) = clip_segment(ends[0], ends[1], xf.rect) { + p.line_segment([a, b], Stroke::new(4.0, t.measure_bg)); + p.line_segment([a, b], Stroke::new(1.5, t.selection)); + } + let along = ends[1] - ends[0]; + let length = along.length(); + if length > 1.0 { + let mid = ends[0] + along * 0.5; + let half = along / length * vectorcraft_tools::trace_split::GRIP_HALF.min(length * 0.5); + p.line_segment([mid - half, mid + half], Stroke::new(7.0, t.measure_bg)); + p.line_segment([mid - half, mid + half], Stroke::new(4.0, t.selection)); + } +} + /// A selected grid repeat's row, column and corner handles and its spacing sliders (#2691), at /// the places the Selection tool's hit testing finds them. pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 7bf5e7ae2a..8f1952367d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3734,6 +3734,8 @@ digits Malayalam Малаялам Outlines Контури Outlines with Source Image Контури с изходно изображение Source Image Изходно изображение + Split View Разделен изглед + Divider Разделител Press and hold to view the source image Задръжте натиснато, за да видите изходното изображение Image Trace View Изглед на трасиране на изображение Snap Options Опции за прилепване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 44c9cb1f42..4ac9342fc4 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2045,6 +2045,8 @@ digits Malayalam Malajalam Snap Curves To Lines Hvataj krive na linije Tracing Result with Outlines Rezultat praćenja s obrisima Source Image Izvorna slika + Split View Podijeljeni prikaz + Divider Razdjelnik Threshold Prag Trace Prati Trace the image with the Default preset Prati sliku zadanim predloškom diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 8deca8492d..4acbf16554 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5099,6 +5099,8 @@ digits Malayalam Malaiàlam Source code on GitHub Codi font a GitHub Source Folder: Carpeta d’origen: Source Image Imatge d’origen + Split View Vista dividida + Divider Divisor Source Sans 3 Source Sans 3 Space After Paragraph Espai després del paràgraf Space Before Paragraph Espai abans del paràgraf diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 26b8adb9b9..279f041bb0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2117,6 +2117,8 @@ digits Malayalam Malajálamské Snap Curves To Lines Přichytit křivky k úsečkám Tracing Result with Outlines Výsledek vektorizace s obrysy Source Image Zdrojový obraz + Split View Rozdělené zobrazení + Divider Dělicí čára Threshold Práh Trace Vektorizovat Trace the image with the Default preset Vektorizovat obraz s přednastavením Výchozí diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b8c3592c2c..57f08cb4eb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4664,6 +4664,8 @@ digits Malayalam Malayalam Snap Curves To Lines Fastgør kurver til linjer Tracing Result with Outlines Vektoriseringsresultat med konturer Source Image Kildebillede + Split View Delt visning + Divider Skillelinje Threshold Tærskel Trace Vektorisér Trace the image with the Default preset Vektorisér billedet med standardforudindstillingen diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d441ebcce3..122d829111 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3825,6 +3825,8 @@ effect Points Punkte Outlines Pfade Outlines with Source Image Pfade mit Quellbild Source Image Quellbild + Split View Geteilte Ansicht + Divider Trennlinie Press and hold to view the source image Gedrückt halten, um das Quellbild anzuzeigen Image Trace View Bildnachzeichner-Ansicht Snap Options Einrastoptionen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2bf92b5aea..9ecee9900d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4500,6 +4500,8 @@ digits Malayalam Μαλαγιάλαμ Tracing Result with Outlines Αποτέλεσμα διανυσματοποίησης με περιγράμματα Outlines with Source Image Περιγράμματα με εικόνα πηγής Source Image Εικόνα πηγής + Split View Διαιρεμένη προβολή + Divider Διαχωριστικό Image Trace View Προβολή διανυσματοποίησης εικόνας Snap Options Επιλογές προσκόλλησης Snap to Glyph Προσκόλληση σε γλυφή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index daf3dcf3f9..68c21b5e42 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3855,6 +3855,8 @@ digits Malayalam Malayálam Outlines Contornos Outlines with Source Image Contornos con imagen de origen Source Image Imagen de origen + Split View Vista dividida + Divider Divisor Press and hold to view the source image Mantén pulsado para ver la imagen de origen Image Trace View Vista del calco de imagen Snap Options Opciones de ajuste diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3328665e11..46b41a9c75 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2088,6 +2088,8 @@ digits Malayalam Malajalam Snap Curves To Lines Tartu käyrät viivoihin Tracing Result with Outlines Jäljitystulos ääriviivoineen Source Image Lähdekuva + Split View Jaettu näkymä + Divider Jakoviiva Threshold Kynnys Trace Jäljitä Trace the image with the Default preset Jäljitä kuva oletusesiasetuksella diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2950c0d453..7f56d4b1f8 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3843,6 +3843,8 @@ digits Malayalam Malayalam Outlines Contours Outlines with Source Image Tracés avec l’image source Source Image Image source + Split View Vue partagée + Divider Séparateur Press and hold to view the source image Maintenez le bouton enfoncé pour afficher l’image source Image Trace View Affichage de la vectorisation de l’image Snap Options Options de magnétisme diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index c9590cb688..3252debcaf 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5467,6 +5467,8 @@ antiAlias Sharp शार्प Source code on GitHub GitHub पर स्रोत कोड Source Folder: स्रोत फ़ोल्डर: Source Image स्रोत इमेज + Split View विभाजित दृश्य + Divider विभाजक Source Sans 3 Source Sans 3 Space After Paragraph पैराग्राफ़ के बाद स्पेस Space Before Paragraph पैराग्राफ़ से पहले स्पेस diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 5f33abcbe2..116b4b0c7e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4547,6 +4547,8 @@ mark-style Japanese Japán Sort by Status Rendezés állapot szerint Source code on GitHub Forráskód a GitHubon Source Image Forráskép + Split View Osztott nézet + Divider Elválasztó Source Sans 3 Source Sans 3 Space After Paragraph Térköz a bekezdés után Space Before Paragraph Térköz a bekezdés előtt diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e4247ba312..d982becfaf 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1888,6 +1888,8 @@ digits Malayalam Malayalam Snap Curves To Lines Kancingkan kurva ke garis Tracing Result with Outlines Hasil penelusuran dengan garis luar Source Image Gambar sumber + Split View Tampilan terbagi + Divider Pembatas Threshold Ambang batas Trace Telusuri Trace the image with the Default preset Telusuri gambar dengan preset Default diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c037ab2c4a..37d1bd3341 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3909,6 +3909,8 @@ digits Malayalam Malayalam Outlines Contorni Outlines with Source Image Contorni con immagine di origine Source Image Immagine di origine + Split View Vista divisa + Divider Divisore Press and hold to view the source image Tieni premuto per visualizzare l'immagine di origine Image Trace View Vista del ricalco immagine Snap Options Opzioni di aggancio diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index dbb32f2827..ece05b2b7c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3657,6 +3657,8 @@ mark-style Japanese 日本式 Outlines アウトライン Outlines with Source Image アウトライン(元画像付き) Source Image 元画像 + Split View 分割表示 + Divider 境界線 Press and hold to view the source image 押している間、元画像を表示 Image Trace View 画像トレースの表示 Snap Options スナップオプション diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8d4ca59a19..b3459b0254 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4068,6 +4068,8 @@ digits Malayalam მალაიალამური Snap Curves To Lines მრუდების ხაზებზე მიბმა Tracing Result with Outlines ვექტორიზაციის შედეგი კონტურებით Source Image საწყისი გამოსახულება + Split View გაყოფილი ხედი + Divider გამყოფი Threshold ზღვარი Trace ვექტორიზაცია Trace the image with the Default preset გამოსახულების ვექტორიზაცია ნაგულისხმევი პრესეტით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index db60a6f5ab..f775c96d24 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3648,6 +3648,8 @@ mark-style Japanese 일본식 Outlines 윤곽선 Outlines with Source Image 원본 이미지 포함 윤곽선 Source Image 원본 이미지 + Split View 분할 보기 + Divider 구분선 Press and hold to view the source image 누르고 있는 동안 원본 이미지 보기 Image Trace View 이미지 추적 보기 Snap Options 스냅 옵션 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 6cef186bd2..5c2cadf9d3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2535,6 +2535,8 @@ digits Malayalam Malayalam Snap Curves To Lines Curves vastzetten op lijnen Tracing Result with Outlines Traceringsresultaat met omlijningen Source Image Bronafbeelding + Split View Gesplitste weergave + Divider Scheidingslijn Threshold Drempel Trace Traceren Trace the image with the Default preset De afbeelding traceren met de standaardvoorinstelling diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e120a0c894..9bf67ab063 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2035,6 +2035,8 @@ digits Malayalam Malajalam Snap Curves To Lines Przyciągaj krzywe do linii Tracing Result with Outlines Wynik obrysu z konturami Source Image Obraz źródłowy + Split View Widok podzielony + Divider Linia podziału Threshold Próg Trace Obrysuj Trace the image with the Default preset Obrysuj obraz ustawieniem Domyślne diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8f1c40f519..7a5c0d785c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4132,6 +4132,8 @@ font-technology Variable Variáveis Outlines Contornos Outlines with Source Image Contornos com imagem de origem Source Image Imagem de origem + Split View Visualização dividida + Divider Divisor Press and hold to view the source image Mantenha pressionado para ver a imagem de origem Image Trace View Exibição de vetorização de imagem Stroke (X), double-click for the Color Picker Traço (X), clique duas vezes para o seletor de cores diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 652c369b27..2f165d657c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3887,6 +3887,8 @@ digits Malayalam Малаялам Outlines Контуры Outlines with Source Image Контуры с исходным изображением Source Image Исходное изображение + Split View Разделённый вид + Divider Разделитель Press and hold to view the source image Удерживайте, чтобы увидеть исходное изображение Image Trace View Просмотр трассировки изображения Snap Options Параметры привязки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 34e9b98622..0fc71a292b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3762,6 +3762,8 @@ digits Malayalam Malayalam Outlines Konturlinjer Outlines with Source Image Konturlinjer med källbild Source Image Källbild + Split View Delad vy + Divider Delningslinje Press and hold to view the source image Håll ned för att visa källbilden Image Trace View Vy för bildkalkering Snap Options Fästalternativ diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 28baed0414..40667eeb42 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3639,6 +3639,8 @@ digits Malayalam Malayalam Outlines Ana hatlar Outlines with Source Image Kaynak Resimli Ana Hatlar Source Image Kaynak Resim + Split View Bölünmüş Görünüm + Divider Ayırıcı Press and hold to view the source image Kaynak resmi görmek için basılı tutun Image Trace View Görüntü İzleme Görünümü Snap Options Yapış Seçenekleri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 64bc112954..a34a3015c4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3902,6 +3902,8 @@ effect Points Точки Outlines Контури Outlines with Source Image Контури з вихідним зображенням Source Image Вихідне зображення + Split View Розділений вигляд + Divider Роздільник Press and hold to view the source image Утримуйте, щоб побачити вихідне зображення Image Trace View Перегляд трасування зображення Snap Options Параметри прив’язки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8575042574..b35a12e341 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4291,6 +4291,8 @@ mark-style Japanese Kiểu Nhật Sort by Status Sắp xếp theo trạng thái Source code on GitHub Mã nguồn trên GitHub Source Image Ảnh nguồn + Split View Chế độ xem chia đôi + Divider Đường chia Source Sans 3 Source Sans 3 Space After Paragraph Khoảng cách sau đoạn văn Space Before Paragraph Khoảng cách trước đoạn văn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 1e048a2b70..ebac9472d9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3712,6 +3712,8 @@ digits Malayalam 马拉雅拉姆数字 Outlines 轮廓 Outlines with Source Image 轮廓(带源图像) Source Image 源图像 + Split View 拆分视图 + Divider 分隔线 Press and hold to view the source image 按住以查看源图像 Image Trace View 图像描摹视图 Snap Options 对齐选项 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 549cf0edbc..787c206753 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5155,6 +5155,8 @@ digits Malayalam 馬來亞拉姆數字 Outlines 外框 Outlines with Source Image 外框(含來源影像) Source Image 來源影像 + Split View 分割檢視 + Divider 分隔線 Press and hold to view the source image 按住以檢視來源影像 Image Trace View 影像描圖檢視 Snap Options 靠齊選項 diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 28c9fe9a78..0d4d326b76 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -241,9 +241,52 @@ fn view_label(v: TraceView) -> &'static str { TraceView::Outlines => tl!("Outlines"), TraceView::OutlinesWithSource => tl!("Outlines with Source Image"), TraceView::Source => tl!("Source Image"), + TraceView::Split => tl!("Split View"), } } +/// The Split view's divider of the one selected Image Trace object, when it shows that view. +fn selected_split(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let [id] = st.selection.objects[..] else { return None }; + st.doc.node(id).filter(|n| is_trace(n) && n.trace_view() == TraceView::Split).map(Node::trace_split) +} + +/// The Divider row of the one selected Image Trace object in the Split view: how much of the +/// source image's width, from its left edge, shows the image. A drag is one undo step, and the +/// arrow keys move it a percent at a time. Nothing without such an object. +pub(crate) fn split_row(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(split) = selected_split(app) else { return }; + ui.horizontal(|ui| { + let label = widgets::dim_label(ui, tl!("Divider")); + // The canvas sets the divider to a ten-thousandth: a hundredth of a percent. + let mut pct = (split * 10_000.0).round() / 100.0; + // Clamping only edits keeps a divider between whole percents (a canvas drag, an agent's + // value) as it is while the panel shows: clamping always rounds it to the step each frame + // and reports a change. + let slider = egui::Slider::new(&mut pct, 0.0..=100.0).suffix("%").step_by(1.0).clamping(egui::SliderClamping::Edits); + let r = widgets::slider(ui, slider).labelled_by(label.id); + r.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), pct, tl!("Divider"))); + if cfg!(test) { + ui.ctx().data_mut(|d| { + d.insert_temp(egui::Id::unique("trace-split-slider-id"), r.id); + d.insert_temp(egui::Id::unique("trace-split-slider-rect"), r.rect); + }); + } + let phase = if r.dragged() && !r.drag_stopped() { + widgets::Live::Dragging + } else if r.drag_stopped() || r.changed() { + widgets::Live::Released + } else { + widgets::Live::Idle + }; + if phase != widgets::Live::Idle { + let split = (pct / 100.0).clamp(0.0, 1.0); + crate::panels::live_run(app, "Image Trace View", "imageTrace.setView", json!({ "view": TraceView::Split.id(), "split": split }), phase); + } + }); +} + /// The View dropdown showing `current` → the view chosen. fn view_dropdown(ui: &mut Ui, current: TraceView, width: f32) -> Option { let labels = TraceView::ALL.map(view_label); @@ -684,6 +727,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } hold_source(app, ui.ctx(), any_trace && r.is_pointer_button_down_on()); }); + split_row(app, ui); ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Mode:")); let mode = st.params["mode"].as_str().unwrap_or("blackAndWhite").to_string(); diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index af2ec39921..15cbffe9e9 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -635,6 +635,106 @@ fn holding_the_eye_button_shows_the_source_image_until_released() { frame(&mut app, &ctx, vec![press(false)]); } +/// In the Split view the panel shows a Divider slider that screen readers find by its name and +/// value; with the keyboard focus on it, → moves the divider a percent, one undo step a press. +/// It is not shown in any other view. +#[test] +fn the_divider_slider_names_and_moves_the_split_views_divider() { + use egui::accesskit::Role; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0)); + let slider_id = egui::Id::unique("trace-split-slider-id"); + let nodes = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect::>()).unwrap_or_default() + }; + let divider = + |tree: &[egui::accesskit::Node]| tree.iter().find(|n| n.role() == Role::Slider && n.label() == Some("Divider")).map(|n| n.numeric_value()); + nodes(&mut app, vec![]); + assert_eq!(divider(&nodes(&mut app, vec![])), None, "no divider in the Tracing Result view"); + app.run("imageTrace.setView", json!({"view": "split", "split": 0.3})).unwrap(); + nodes(&mut app, vec![]); + assert_eq!(divider(&nodes(&mut app, vec![])), Some(Some(30.0))); + let id = ctx.data(|d| d.get_temp::(slider_id)).expect("the slider's id"); + ctx.memory_mut(|m| m.request_focus(id)); + nodes(&mut app, vec![]); + let steps = app.session.active().unwrap().history.undo.len(); + let right = Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + nodes(&mut app, vec![right.clone()]); + assert_eq!(first_selected(&app).unwrap().trace_split(), 0.31); + nodes(&mut app, vec![right]); + assert_eq!(first_selected(&app).unwrap().trace_split(), 0.32); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 2, "one undo step a press"); + assert_eq!(divider(&nodes(&mut app, vec![])), Some(Some(32.0))); +} + +/// A divider between whole percents (as a canvas drag or an agent sets it) stays as it is while +/// the panel shows, with no undo step; dragging the Divider slider sets it as one undo step. +#[test] +fn the_divider_slider_keeps_an_exact_divider_and_a_drag_is_one_undo_step() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0)); + let run = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + app.run("imageTrace.setView", json!({"view": "split", "split": 0.3025})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + for _ in 0..3 { + run(&mut app, vec![]); + } + assert_eq!(first_selected(&app).unwrap().trace_split(), 0.3025, "the panel leaves the divider as it is"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "no undo step"); + let rect = ctx.data(|d| d.get_temp::(egui::Id::unique("trace-split-slider-rect"))).expect("the slider's rect"); + let at = |f: f32| Pos2::new(rect.left() + rect.width() * f, rect.center().y); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![Event::PointerMoved(at(0.3)), button(at(0.3), true)]); + for f in [0.4, 0.6, 0.8] { + run(&mut app, vec![Event::PointerMoved(at(f))]); + } + run(&mut app, vec![button(at(0.8), false)]); + run(&mut app, vec![]); + let split = first_selected(&app).unwrap().trace_split(); + assert!(split > 0.6, "the drag moved the divider: {split}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step for the drag"); +} + +/// Properties shows the Divider slider of the selected Image Trace object in the Split view only, +/// with its name and value for screen readers. +#[test] +fn properties_shows_the_divider_slider_in_the_split_view() { + use egui::accesskit::Role; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0)); + let divider = |app: &mut VectorcraftApp| { + let mut found = None; + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + crate::panels::properties::show(app, ui); + }); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + found = nodes.iter().find(|(_, n)| n.role() == Role::Slider && n.label() == Some("Divider")).map(|(_, n)| n.numeric_value()); + } + found + }; + assert_eq!(divider(&mut app), None, "no divider in the Tracing Result view"); + app.run("imageTrace.setView", json!({"view": "split", "split": 0.4})).unwrap(); + assert_eq!(divider(&mut app), Some(Some(40.0))); +} + /// With another object first in the selection, the eye button and the panel menu's Release /// act on the selected Image Trace object. #[test] diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 02870c371f..52b74a5fb5 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -377,6 +377,7 @@ fn trace_section(app: &mut VectorcraftApp, ui: &mut Ui, preset: &str, view: vect crate::panels::image_trace::preset_dropdown(app, ui, preset, ui.available_width()); }); ui.horizontal(|ui| crate::panels::image_trace::view_row(app, ui, view, ui.available_width())); + crate::panels::image_trace::split_row(app, ui); if widgets::flat_button(ui, tl!("Image Trace"), ui.available_width()).clicked() { crate::panels::image_trace::open_settings(app); } diff --git a/docs/mcp.md b/docs/mcp.md index 8f99e37173..9fa31874f9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4495,6 +4495,13 @@ already walks Image Trace. Short agent entry points: - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. + `imageTrace.setView {view: "split", split?}` is VectorCraft's own view: the window shows the source image on the part of + the image left of a divider across it and the tracing result everywhere else. `split` (0 to 1, default 0.5) is the fraction of the source + image's width, measured from its left edge in its own pixels, that shows the image, so the divider turns with the + image; a value outside 0 to 1, or one that is not a number, is an error. The object keeps `split` when another view is + set and when it is traced again, and the result names it. Exports, printing and Expand draw the tracing result. With + one such object selected, the Selection tool drags the divider (one undo step), and the Image Trace and Properties + panels show a Divider slider that the arrow keys move a percent at a time. With `byColor: true`, `imageTrace.expand` and `imageTrace.makeAndExpand` put each color's paths in a group of their own, named by the global swatch the color links to (a tint with its percentage, as `Sky 50%`) or as `#rrggbb`; gradient fills share a group named `Gradients`. The groups stack in the order of the lowest path in each, and each diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1cb893faa4..16d6fff7d8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1823,6 +1823,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly; on edges blurred by 1 to 3 pixels, the pixel also counts as on that edge when paths of up to 5 steps through pixels that keep getting darker and lighter reach past the gray both ways, and black and white then lie as near as the steps to them, so the same disc and square trace with one gray path at blurs of 1 and 2 pixels and with at most 4 slivers of up to 3 pixels in a light gray at 1.5 pixels, where up to 33 gray paths were traced before (at a blur of 3 pixels with the colors named, a gray of 200 leaves 4 slivers with no area and a light gray of 230 leaves 8 small slivers, where 11 and 14 gray paths were traced before; pixel noise of a level or more can still leave gray slivers); when the first step toward black or white already comes to that color, the path the other way stops at a pixel of the gray, so with edges blurred by 0.6 pixels a gray band 3 to 8 pixels wide along black traces gray at no fewer than 4 of every 5 of its pixel centers; with sharp edges, gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide lying along black traces as black and white, and a short one about three pixels wide can lose most or all of its gray); on edges blurred by a pixel or more, a soft-edged gray band up to 4 pixels wide along black traces as black and white, with gray at no more than 1 of every 16 of its pixel centers, at blurs of 1.5 and 2 pixels, a light gray stroke 2 pixels wide and 2 pixels from black, blurred by 1.5 pixels, traces gray at about 10 of the 34 pixel centers along its middle and one 4 pixels away at about 25, and a soft-edged gray stroke running out of black, blurred by 1 or 1.5 pixels, loses 3 or 4 of the 16 pixel centers along its middle nearest black; a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color beyond both colors of an edge:** an edge pixel between a gray panel and a charcoal disc on a paler gray ground is read as a blend of the panel and the disc, not of the ground and the disc, when the pixels beside it lie on each side of it, none lies past the panel toward the ground, and lighter pixels lead from it to the panel's color or to a flat area of the panel, so the disc traces with three paths, one per color, with the colors found or named, instead of with 28 slivers of the ground around it when its edges are sharp and one sliver when they are blurred by 0.7 pixel (an edge blurred by a pixel or more can still leave slivers of the ground); the pixels of a pale line on the disc, one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their blends; code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. +- **Image Trace, Split View:** VectorCraft's own View shows the source image on the part of the image left of a divider and the tracing result everywhere else; the Selection tool drags the divider on the canvas (one undo step, Escape cancels), the Image Trace and Properties panels set it with a Divider slider, and `imageTrace.setView {view: "split", split}` sets it for agents, while exports, printing and Expand keep the result; tests in `crates/render`, `crates/engine`, `crates/tools` and `crates/ui-egui`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More, split into at least one color per step of Color detail before colors that look alike merge), Automatic (flat art with its own colours, else as many as the tones need; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)).