diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index 24c274846b..064fb3b5cf 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -6,7 +6,7 @@ //! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also //! take the comma-separated legacy form (). //! Hues take the angle units of CSS Values 4 (). A hex -//! color may leave out its `#`. +//! color may leave out its `#`. [`format`] writes a color in these forms. //! //! The module reads a subset of CSS. A function's arguments are literal numbers, percentages, //! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`, @@ -89,6 +89,126 @@ fn byte(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } +/// The forms [`format`] writes a color in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Notation { + /// `#rrggbb`. + Hex, + /// `#rrggbbaa`, `ff` for a color without an alpha. + HexAlpha, + /// `rgb(51 102 153)`. + Rgb, + /// `hsl(210 50% 40%)`. + Hsl, + /// `oklch(49.93% 0.0987 250.43)`. + Oklch, +} + +/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation` +/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of +/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form +/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and +/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and +/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a +/// gray is 0. [`Notation::Hex`] leaves the alpha out. +pub fn format(rgb: [f32; 3], alpha: Option, notation: Notation) -> String { + // A NaN alpha reads as none. + let alpha = alpha.filter(|a| !a.is_nan()); + let bytes = rgb.map(byte); + let units = bytes.map(|v| f64::from(v) / 255.0); + let [r, g, b] = bytes; + match notation { + Notation::Hex => hex_of(rgb), + Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))), + Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)), + Notation::Hsl => { + let [h, s, l] = rgb_to_hsl(units); + format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha)) + } + Notation::Oklch => { + let lch = oklab::to_oklch(units.map(|v| v as f32)); + // The fewest places that read back to the same bytes, from two (four for chroma). + let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes); + let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch))); + let places = |base: i32| usize::try_from(base + p).unwrap_or(2); + let c = number(c, places(4)); + // A chroma that rounds to 0 is a gray, whose hue is 0. + let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) }; + format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha)) + } + } +} + +/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the +/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under +/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of +/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at +/// the rounded lightness and hue; the chroma is lowered a step at a time instead. +fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> { + let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra)); + let step = 10f64.powi(-(4 + extra)); + let mut c = rounded(c, 4 + extra); + for _ in 0..OKLCH_CHROMA_STEPS { + if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) { + return Some([l, c.max(0.0), h]); + } + c = rounded(c - step, 4 + extra); + } + None +} + +/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB. +const OKLCH_CHROMA_STEPS: usize = 50; + +/// `v` rounded to `places` decimal places. +fn rounded(v: f64, places: i32) -> f64 { + let f = 10f64.powi(places); + (v * f).round() / f +} + +/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing. +fn alpha_part(alpha: Option) -> String { + let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2); + if percent == "100" { String::new() } else { format!(" / {percent}%") } +} + +/// A hue in degrees to two places, 360 written as 0. +fn hue_text(h: f64) -> String { + hue_text_to(h, 2) +} + +/// A hue in degrees to `places` places, 360 written as 0. +fn hue_text_to(h: f64, places: usize) -> String { + let text = number(h, places); + if text == "360" { "0".to_string() } else { text } +} + +/// `v` to `places` decimal places, without trailing zeros or a sign on zero. +fn number(v: f64, places: usize) -> String { + let text = format!("{v:.places$}"); + let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() }; + if text == "-0" { "0".to_string() } else { text.to_string() } +} + +/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's +/// rgbToHsl (); the hue of a gray is 0. +fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] { + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let (d, l) = (max - min, (max + min) / 2.0); + if d == 0.0 { + return [0.0, 0.0, l]; + } + let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) }; + let h = if max == r { + (g - b) / d + if g < b { 6.0 } else { 0.0 } + } else if max == g { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + [h * 60.0, s, l] +} + /// A hex color of 3, 4, 6 or 8 digits, with or without `#`. fn hex(text: &str) -> Option { let digits = text.strip_prefix('#').unwrap_or(text); @@ -412,6 +532,26 @@ mod tests { assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00"); } + #[test] + fn format_writes_each_notation_with_the_alpha_where_it_belongs() { + let rgb = [0.2, 0.4, 0.6]; + let half = Some(0.5); + assert_eq!(format(rgb, half, Notation::Hex), "#336699"); + assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980"); + assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff"); + assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff"); + assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)"); + assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)"); + assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out"); + assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)"); + assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)"); + assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)"); + assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)"); + assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)"); + assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)"); + assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)"); + } + proptest! { #[test] fn random_text_never_panics(text in "\\PC{0,60}") { @@ -439,5 +579,23 @@ mod tests { prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a)); prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}")); } + + #[test] + fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) { + let rgb = [r, g, b].map(|v| f32::from(v) / 255.0); + let alpha = f32::from(a) / 255.0; + for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] { + let text = format(rgb, Some(alpha), notation); + let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse")); + prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text); + let read = c.alpha.unwrap_or(1.0); + match notation { + Notation::Hex => prop_assert_eq!(c.alpha, None), + Notation::HexAlpha => prop_assert_eq!(byte(read), a), + // A percentage to two places, left out when it rounds to 100. + _ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read), + } + } + } } } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index dd18bcadcb..4a4b998782 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -146,6 +146,15 @@ pub fn specs() -> Vec { always, parse_color ), + cmd!( + query "color.format", + "Format Color", + [], + None, + "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four), and oklch() takes up to two more where fewer would read back to another color; cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", + always, + format_color + ), cmd!( query "color.contrast", "Contrast", @@ -158,6 +167,31 @@ pub fn specs() -> Vec { ] } +fn format_color(_: &mut Session, p: &Value) -> Result { + const C: &str = "color.format"; + let col = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?; + let opacity = super::paint::opacity_param(p, C)?; + let notation = match text_param(p, "notation", C)? { + Some("hex") => Some(css::Notation::Hex), + Some("hexAlpha") => Some(css::Notation::HexAlpha), + Some("rgb") => Some(css::Notation::Rgb), + Some("hsl") => Some(css::Notation::Hsl), + Some("oklch") => Some(css::Notation::Oklch), + Some("cmyk") => None, + _ => return Err(bad(C, "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk")), + }; + let cms = vectorcraft_color::cms::active(); + let intent = cms.settings().intent; + let text = match notation { + None => vectorcraft_doc::swatches::color_name(cms.convert(&col, Model::Cmyk, intent)), + Some(css::Notation::Oklch) if !cms.rgb_is_srgb() => return Err(bad(C, "OKLCH needs sRGB as the working RGB space")), + // The working RGB numbers, as the Color panel's hex field and color.parse read them; for + // oklch() the working RGB space is sRGB. + Some(n) => css::format(cms.convert(&col, Model::Rgb, intent).to_rgb_uncalibrated(), opacity, n), + }; + Ok(json!({ "text": text })) +} + fn parse_color(_: &mut Session, p: &Value) -> Result { const C: &str = "color.parse"; let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?; diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 660df05f71..4f498e972a 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -91,6 +91,8 @@ //! deselects it as before), Global Edit ends when fewer than two members are left, and leaving //! one out is not an undo step. +use std::sync::Arc; + use serde::Serialize; use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer}; @@ -214,8 +216,18 @@ struct Form { frame: Affine, } +#[cfg(test)] +thread_local! { + /// Tests: how many times [`Form::of`] reduced an object to its form on this thread. + pub(crate) static FORMS_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread. + pub(crate) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + impl Form { fn of(n: &Node) -> Option { + #[cfg(test)] + FORMS_MADE.with(|c| c.set(c.get() + 1)); let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY }; f.add(n, 0)?; let first = *f.points.first()?; @@ -450,8 +462,8 @@ fn matches(s: &Session, o: &Options) -> Result> { ), }; let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center()); - let in_scope = |n: &Node| { - let Some(b) = n.geometric_bounds_with(&symbols) else { return false }; + let in_scope = |b: Option| { + let Some(b) = b else { return false }; if !d.artboards.iter().any(|a| on(a.rect, b)) { return o.include_canvas; } @@ -459,14 +471,16 @@ fn matches(s: &Session, o: &Options) -> Result> { }; // A copy that lies the same way has the size of the selected object when their boxes are as // wide and as high; a turned copy, when the transform that lays the object on it doesn't scale. - let same_size = |n: &Node, xf: Affine, turned: bool| { + let same_size = |b: Option, xf: Affine, turned: bool| { if turned { close(xf.determinant().abs().sqrt(), 1.0) } else { - matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)) + matches!((key_size, b), (Some((w, h)), Some(b)) if close(w, b.width()) && close(h, b.height())) } }; let mut out = vec![(*id, Affine::IDENTITY)]; + let mut cache = st.global_edit_forms.0.borrow_mut(); + let mut pass = cache.forms.pass(); super::select::walk_selectable(d, st.isolation, |n| { if n.id == *id || out.len() >= MAX_MEMBERS { return false; @@ -482,21 +496,134 @@ fn matches(s: &Session, o: &Options) -> Result> { _ => false, }; // The object count first: it turns most objects down before their form is made. - if n.children().map(Vec::len) == count - && let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n)) - && (!o.size || same_size(n, xf, turned)) - && (!o.appearance || same_look(key, n)) - && in_scope(n) - { - out.push((n.id, xf)); - // A group taken is taken whole, as compound paths, symbol instances and the others are. - return false; + if n.children().map(Vec::len) != count { + return look_in; + } + let seen = pass.get(n, || Seen { form: Form::of(n).filter(|_| supported(n)), bounds: None }); + if let Some((xf, turned)) = seen.form.as_ref().and_then(|f| form.onto(f)) { + let b = seen.bounds(n, &symbols); + if (!o.size || same_size(b, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(b) { + out.push((n.id, xf)); + // A group taken is taken whole, as compound paths, symbol instances and the others are. + return false; + } } look_in }); + cache.forms.end(pass, d); Ok(out) } +/// What [`matches`] and [`outlines`] found for each object they looked at, kept from one call to +/// the next so that after an edit only the objects the edit replaced are measured again. A clone +/// starts empty. +#[derive(Default)] +pub struct FormCache(std::cell::RefCell); + +#[derive(Default)] +struct FormCacheInner { + forms: ByNode, + /// The outline of each highlighted object, or `None` when it has none and its box is shown. + outlines: ByNode>, +} + +/// An object as [`matches`] found it. +struct Seen { + /// Its form, or `None` when Global Edit doesn't support it. + form: Option
, + /// Its geometric bounds, once measured; not kept for an object with symbol instances, whose + /// bounds follow the symbols' art. + bounds: Option>, +} + +impl Seen { + fn bounds(&mut self, n: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> Option { + if self.form.as_ref().is_some_and(|f| !f.symbols.is_empty()) { + return n.geometric_bounds_with(symbols); + } + *self.bounds.get_or_insert_with(|| n.geometric_bounds_with(symbols)) + } +} + +/// Values found for nodes of a document, by node address. The layers they were found in are held, +/// which keeps every node in them alive and unchanged (an edit replaces each node it changes), so +/// no other node can have that address while its entry is here. +struct ByNode { + layers: Vec>, + values: ByAddress, +} + +impl Default for ByNode { + fn default() -> Self { + Self { layers: vec![], values: ByAddress::default() } + } +} + +/// Values by node address. +type ByAddress = std::collections::HashMap>; + +/// Hashes a node address: a multiply that spreads its bits, with the high half folded into the low +/// half (addresses are aligned, so their low bits are always the same). +#[derive(Default)] +struct AddressHasher(u64); + +impl std::hash::Hasher for AddressHasher { + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3); + } + } + + fn write_usize(&mut self, n: usize) { + let x = (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15); + self.0 = x ^ (x >> 32); + } + + fn finish(&self) -> u64 { + self.0 + } +} + +/// One walk of a document: the values it asks for, taken from the ones kept or found anew. +struct Pass { + old: ByAddress, + new: ByAddress, +} + +impl Pass { + fn get(&mut self, n: &Node, find: impl FnOnce() -> T) -> &mut T { + let at = std::ptr::from_ref(n) as usize; + let old = &mut self.old; + self.new.entry(at).or_insert_with(|| old.remove(&at).unwrap_or_else(find)) + } +} + +impl ByNode { + fn pass(&mut self) -> Pass { + let old = std::mem::take(&mut self.values); + Pass { new: ByAddress::with_capacity_and_hasher(old.len(), Default::default()), old } + } + + /// Keep the values `pass` asked for, found in `d`. + fn end(&mut self, pass: Pass, d: &Document) { + self.values = pass.new; + self.layers.clone_from(&d.layers); + } +} + +impl Clone for FormCache { + fn clone(&self) -> Self { + Self::default() + } +} + +impl std::fmt::Debug for FormCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let c = self.0.borrow(); + f.debug_struct("FormCache").field("forms", &c.forms.values.len()).field("outlines", &c.outlines.values.len()).finish() + } +} + fn can_toggle(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.global_edit.is_some() { @@ -935,20 +1062,45 @@ pub fn similar(s: &Session) -> Outlines { /// selected object, in their layer's color. fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines { let symbols = st.doc.symbol_boxes(); - members + let mut cache = st.global_edit_forms.0.borrow_mut(); + let mut pass = cache.outlines.pass(); + let out = members .iter() .filter_map(|(id, _)| { - let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?; - if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) { - return None; + // One look-up of the object's place, then down through its layers and groups: none of + // them may be selected, and the innermost layer gives the color. + let (mut nodes, mut found, mut layer) = (&st.doc.layers, None, None); + for i in st.doc.index_path(*id)? { + let c: &Node = nodes.get(i)?; + if st.selection.objects.contains(&c.id) { + return None; + } + if c.is_layer() { + layer = Some(c); + } + if let Some(ch) = c.children() { + nodes = ch; + } + found = Some(c); } - let path = match n.stroke_path() { - Some(p) => p, + let n = found.filter(|n| n.id == *id && !holds(n, &st.selection.objects))?; + let color = match layer.map(|l| &l.kind) { + Some(NodeKind::Layer { color, .. }) => color.rgb(), + _ => vectorcraft_doc::LAYER_COLORS[0].1, + }; + let path = match pass.get(n, || { + #[cfg(test)] + OUTLINES_MADE.with(|c| c.set(c.get() + 1)); + n.stroke_path() + }) { + Some(p) => p.clone(), None => n.geometric_bounds_with(&symbols)?.to_path(0.1), }; - Some((path, st.doc.layer_color(*id))) + Some((path, color)) }) - .collect() + .collect(); + cache.outlines.end(pass, &st.doc); + out } #[cfg(test)] diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 88ee200c2c..c722e2a58b 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -913,9 +913,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result { apply_paint_opacity(s, p, paint, opacity, fill) } -/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None` -/// when it is left out or null. -fn opacity_param(p: &Value, cmd: &str) -> Result> { +/// The `opacity` param of `paint.setFill`, `paint.setStroke` and `color.format` (a percentage) as +/// 0..1; `None` when it is left out or null. +pub(crate) fn opacity_param(p: &Value, cmd: &str) -> Result> { match p.get("opacity") { None | Some(Value::Null) => Ok(None), Some(v) => match v.as_f64() { diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 99d6cc60b9..61406fdc61 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::BlendMode; use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer}; -use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject}; +use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject}; use vectorcraft_geom::{FillRule, PathData, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, PathfinderOp}; @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Clean Up…", ["Object", "Path"], None, - "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}", + "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers, objects at 0% opacity and their members, and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}", has_doc, clean_up ), @@ -1715,12 +1715,152 @@ fn is_painted(a: &Appearance) -> bool { }) } +/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value. +pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4; +/// The widths Hairline Slivers takes, in points. +pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive = 0.001..=3.0; + +/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string +/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`]. +pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result { + let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH); + if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) { + let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end()); + return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt"))); + } + Ok(w) +} + +/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths +/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke), +/// whose fill no circle `width` across fits inside? A compound path is measured as one fill. +/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]). +/// A hidden member of a compound path is measured too, since the compound path paints it. +fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option { + // A shape with no fill that paints is left to Unpainted Objects. + if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) { + return Some(false); + } + let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind { + NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule), + NodeKind::Compound { children, rule } => { + let mut all = vec![]; + for c in children { + let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) }; + all.extend(path.subpaths.iter()); + } + (all, *rule) + } + _ => return Some(false), + }; + // Paths of one anchor are stray points, and open paths are lines. + if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) { + return Some(false); + } + po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget) +} + +/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an +/// effect on the object or on one of its fills and strokes? +fn draws_beyond_its_fill(a: &Appearance) -> bool { + a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty()) +} + +/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a +/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping +/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers +/// leaves its members alone. +fn holds_generated_art(n: &Node) -> bool { + let e = n.extras(); + vectorcraft_tools::builder::is_live_paint(n) + || e.type_outlines + || e.clip_pieces + || e.graph.is_some() + || e.shaper.is_some() + || e.dimension.is_some() + || e.flare.is_some() + || e.trace.is_some() + || e.objects_on_path.is_some() + || e.live_paint_gaps.is_some() + || e.compound_shape +} + +/// The objects Hairline Slivers finds in `d` for `width`. +pub(crate) struct Slivers { + pub ids: Vec, + /// Closed paths and compound paths whose fill couldn't be measured, which are left as they are. + pub unmeasured: Vec, +} + +/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any. +pub(crate) fn unmeasured_warning(count: usize) -> Option { + (count > 0).then(|| { + format!( + "Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are" + ) + }) +} + +/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not +/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and +/// groups of the whole document. A compound path counts as one object. The clipping paths of groups +/// and layers (and all of a clipping group used as one), the members of live and generated art, +/// objects at 0 % opacity and everything in a group or layer at 0 %, and the members of groups and +/// layers whose own stroke or effect paints them are left out. +pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers { + struct Walk<'a> { + width: f64, + locks: LockedArtboards<'a>, + within: &'a dyn Fn(NodeId) -> bool, + // One budget for the whole document, so that thousands of shapes that need a search take + // a bounded time; the shapes after it runs out count as unmeasured. + budget: po::ThicknessBudget, + out: Vec<(NodeId, Option)>, + } + fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) { + // An object at 0 % opacity, or anything in a group or layer at 0 %, paints nothing. + if !n.visible || n.locked || n.is_template() || clip_path || n.opacity <= 0.0 { + return; + } + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { + if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) { + return; + } + let clips = n.clips(); + for (i, c) in children.iter().enumerate() { + visit(c, clips && i == 0, w); + } + } + // Art on a locked artboard, or outside `within`, is left out before it is measured. + NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => { + match is_hairline_sliver(n, w.width, &mut w.budget) { + Some(false) => {} + found => w.out.push((n.id, found)), + } + } + _ => {} + } + } + let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] }; + for l in &d.layers { + visit(l, false, &mut w); + } + let mut found = w.out; + let editable = d.editable(); + found.retain(|(id, _)| editable(*id)); + let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some()); + Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() } +} + fn clean_up(s: &mut Session, p: &Value) -> Result { const C: &str = "object.path.cleanUp"; let stray = switch_or(p, "strayPoints", true, C)?; let unpainted = switch_or(p, "unpaintedObjects", true, C)?; let empty_text = switch_or(p, "emptyTextPaths", true, C)?; - let found = { + let slivers = switch_or(p, "hairlineSlivers", false, C)?; + let width = sliver_width(p, "sliverWidth", C)?; + let (found, warning) = { let d = &s.doc()?.doc; let mut v = vec![]; fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec, opts: (bool, bool, bool)) { @@ -1763,10 +1903,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } let editable = d.editable(); v.retain(|id| editable(*id)); - v + let mut warning = None; + if slivers { + let found = hairline_slivers(d, width, &|_| true); + let listed: BTreeSet = v.iter().copied().collect(); + // A shape another option removes isn't left as it is. + warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count()); + v.extend(found.ids.into_iter().filter(|id| !listed.contains(id))); + } + (v, warning) + }; + let reply = |removed: usize| match &warning { + Some(w) => json!({ "removed": removed, "warning": w }), + None => json!({ "removed": removed }), }; if found.is_empty() { - return Ok(json!({ "removed": 0 })); + return Ok(reply(0)); } s.edit("Clean Up", |d, _| { let mut gone = Beside::replacing(d, &found); @@ -1777,7 +1929,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } gone.finish(d) })?; - Ok(json!({ "removed": found.len() })) + Ok(reply(found.len())) } // ---------- Divide Objects Below ---------- diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 612cf436b7..c2699f219c 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -152,6 +152,7 @@ pub(super) const ALLOWED: &[&str] = &[ "charStyle.setAttrs", "charStyle.unused", "color.convert", + "color.format", "color.gamutCheck", "color.harmony", "color.parse", @@ -541,6 +542,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.object.brushStrokes", "select.object.clippingMasks", "select.object.directionHandles", + "select.object.hairlineSlivers", "select.object.notAlignedToPixelGrid", "select.object.pointText", "select.object.slices", diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index eb504b6074..931504dedb 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint; use super::object::can_align; use super::panelcmds::artboard_at; +use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning}; use super::wand::{fill_of, stroke_of}; use super::{ CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param, @@ -205,6 +206,15 @@ pub fn specs() -> Vec { cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| p.anchor_count() == 1))), + cmd!( + "select.object.hairlineSlivers", + "Hairline Slivers…", + ["Select", "Object"], + None, + "{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, objects at 0% opacity and their members, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}", + has_doc, + select_hairline_slivers + ), cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| !p.is_closed()))), @@ -1459,6 +1469,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result { Ok(json!({ "count": s.doc()?.selection.objects.len() })) } +/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes +/// ([`hairline_slivers`]), inside the isolated group while one is isolated. +fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result { + const C: &str = "select.object.hairlineSlivers"; + let width = sliver_width(p, "width", C)?; + let st = s.doc()?; + let (d, iso) = (&st.doc, st.isolation); + let locks = d.locked_artboards(); + let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id)); + let warning = unmeasured_warning(found.unmeasured.len()); + s.select(|_, sel| sel.set(found.ids))?; + let count = s.doc()?.selection.objects.len(); + Ok(match warning { + Some(w) => json!({ "count": count, "warning": w }), + None => json!({ "count": count }), + }) +} + /// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned /// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk /// does not look at the paths inside it. diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 4f05e615af..e1bb6df83a 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -86,6 +86,9 @@ pub struct DocState { /// Whether Start Global Edit supports the one selected object /// ([`cmd::globaledit::SupportCache`]), as of a revision. Not saved, not undoable. pub(crate) global_edit_support: cmd::globaledit::SupportCache, + /// The forms Start Global Edit compared the selected object with + /// ([`cmd::globaledit::FormCache`]). Not saved, not undoable. + pub(crate) global_edit_forms: cmd::globaledit::FormCache, /// What leaving symbol editing mode goes back to ([`cmd::symboledit`]). pub(crate) symbol_edit_return: cmd::symboledit::Return, pub interaction: Option, @@ -481,6 +484,7 @@ impl DocState { global_edit: None, similar_outlines: Default::default(), global_edit_support: Default::default(), + global_edit_forms: Default::default(), symbol_edit_return: Default::default(), interaction: None, undo_group: None, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2cdb0f6239..48964aad0c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -33,7 +33,7 @@ pub use cmd::flare::flare_settings; pub use cmd::gradient::{GradientEditPaints, StopOwner}; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; -pub use cmd::pathops::{auto_simplify_level, can_outline_stroke}; +pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level, can_outline_stroke}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE; diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index e16542edb2..46d03c0379 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -399,6 +399,73 @@ fn parse_err(s: &mut Session, p: Value) -> String { s.execute("color.parse", &p).unwrap_err().to_string() } +/// `color.format` writes each notation, with the opacity only where it belongs, and `color.parse` +/// reads every notation but CMYK back to the same color and opacity. +#[test] +fn format_writes_each_notation_and_parse_reads_it_back() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let s = &mut s; + let fmt = |s: &mut Session, color: Value, opacity: Value, notation: &str| { + let r = s.execute("color.format", &json!({ "color": color, "opacity": opacity, "notation": notation })).unwrap(); + r["text"].as_str().unwrap().to_string() + }; + let blue = json!("#336699"); + for (notation, at_half, at_full) in [ + ("hex", "#336699", "#336699"), + ("hexAlpha", "#33669980", "#336699ff"), + ("rgb", "rgb(51 102 153 / 50%)", "rgb(51 102 153)"), + ("hsl", "hsl(210 50% 40% / 50%)", "hsl(210 50% 40%)"), + ] { + assert_eq!(fmt(s, blue.clone(), json!(50), notation), at_half, "{notation}"); + assert_eq!(fmt(s, blue.clone(), Value::Null, notation), at_full, "{notation}"); + } + let oklch = fmt(s, blue.clone(), json!(25), "oklch"); + assert!(oklch.starts_with("oklch(") && oklch.ends_with(" / 25%)"), "{oklch}"); + // The working CMYK numbers through the color settings, as color.convert gives them. + let cmyk = s.execute("color.convert", &json!({ "color": "#336699", "to": "cmyk" })).unwrap(); + let pct: Vec = cmyk["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect(); + let expected = format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3]); + assert_eq!(expected, "C=87 M=61 Y=19 K=0", "the default color settings, as docs/mcp.md gives them"); + assert_eq!(fmt(s, blue.clone(), json!(50), "cmyk"), expected); + assert_eq!(fmt(s, json!({"c": 10, "m": 20, "y": 30, "k": 0}), Value::Null, "cmyk"), "C=10 M=20 Y=30 K=0", "a CMYK color keeps its values"); + assert_eq!(fmt(s, json!({"gray": 40}), Value::Null, "cmyk"), "C=0 M=0 Y=0 K=40"); + for color in [json!("#336699"), json!("#0a0b0c"), json!("#ff0000"), json!("#ffffff"), json!({"c": 100, "m": 0, "y": 0, "k": 0})] { + for (notation, opacity) in [("hex", Value::Null), ("hexAlpha", json!(40)), ("rgb", json!(12.5)), ("hsl", json!(99.99)), ("oklch", json!(0))] { + let text = fmt(s, color.clone(), opacity.clone(), notation); + let shown = fmt(s, color.clone(), Value::Null, "hex"); + let r = s.execute("color.parse", &json!({ "text": text })).unwrap(); + assert_eq!(r["hex"], json!(shown), "{color} {notation}: {text}"); + match notation { + "hex" => assert_eq!(r["opacity"], Value::Null, "{text}"), + "hexAlpha" => assert_eq!(r["opacity"], json!(40.0), "{text}"), + _ => assert_eq!(r["opacity"], opacity.as_f64().map_or(Value::Null, |o| json!(o)), "{text}"), + } + } + } +} + +/// `color.format` refuses a missing or wrong color, opacity or notation. +#[test] +fn format_refuses_bad_params() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let mut err = |p: Value| s.execute("color.format", &p).unwrap_err().to_string(); + let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk"; + assert!(err(json!({"color": "#336699"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": "css"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": "HEX"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": 1})).ends_with("`notation` must be a string")); + assert!(err(json!({"notation": "hex"})).ends_with("missing or invalid `color`")); + assert!(err(json!({"color": "#33669980", "notation": "hex"})).ends_with("missing or invalid `color`")); + for opacity in [json!(-1), json!(101), json!("50"), json!(true)] { + assert!( + err(json!({"color": "#336699", "opacity": opacity, "notation": "rgb"})).ends_with("`opacity` must be a number from 0 to 100"), + "{opacity}" + ); + } +} + #[test] fn assign_profile_is_stored_and_undoable() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index 3bfe6039fa..ae56fa7c5a 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -119,6 +119,43 @@ fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts assert!(highlights(&s).is_empty(), "two objects selected"); } +#[test] +fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() { + use crate::cmd::globaledit::{FORMS_MADE, OUTLINES_MADE, highlights}; + let made = || (FORMS_MADE.with(std::cell::Cell::get), OUTLINES_MADE.with(std::cell::Cell::get)); + let since = |b: (usize, usize)| { + let n = made(); + (n.0 - b.0, n.1 - b.1) + }; + let mut s = session(); + let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let copies: Vec = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0)).collect(); + sel(&mut s, &[key]); + let before = made(); + assert_eq!(highlights(&s).len(), 39); + assert_eq!(since(before), (40, 39), "the first preview measures each object"); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let before = made(); + assert_eq!(highlights(&s).len(), 39); + assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged"); + sel(&mut s, &[copies[0]]); + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + sel(&mut s, &[copies[1]]); + s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap(); + sel(&mut s, &[copies[2]]); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + sel(&mut s, &[key]); + let before = made(); + let shown = highlights(&s); + assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar"); + assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match"); + let moved = node(&s, copies[1]).stroke_path().unwrap(); + assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now"); + s.execute("select.globalEditOptions", &json!({"size": true})).unwrap(); + assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out"); + assert_eq!(crate::cmd::globaledit::match_count(&s), 38); +} + #[test] fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() { let mut s = session(); diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 78e75dba1d..f4e251638f 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1066,6 +1066,339 @@ fn clean_up_removes_junk() { assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none()); } +/// A path drawn by `d`, filled black with no stroke. +fn filled(s: &mut Session, d: &str) -> NodeId { + let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()); + fill_only(s, id); + id +} + +fn fill_only(s: &mut Session, id: NodeId) { + s.edit("t", |d, _| { + d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into(); + Ok(()) + }) + .unwrap(); +} + +/// Hairline Slivers' test art: (the slivers, the shapes with a width). +fn sliver_art(s: &mut Session) -> (Vec, Vec) { + // A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide + // and tall. A long one across the page. A compound path of two slivers. + let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z"); + let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z"); + let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z"); + let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z"); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, two); + // Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it + // draws a line), an open path, and a compound path of a sliver and a square. + let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z"); + let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, dot); + let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into(); + Ok(()) + }) + .unwrap(); + let open = filled(s, "M500 10 L540 40 L500.001 10.0015"); + let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z"); + let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z"); + s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap(); + let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, mixed); + s.execute("select.none", &json!({})).unwrap(); + (vec![triangle, long, two], vec![strip, dot, stroked, open, mixed]) +} + +#[test] +fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() { + let mut s = session(); + let (slivers, kept) = sliver_art(&mut s); + // Off by default. + assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0); + // A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is + // at 0 % opacity paints nothing either. + let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z"); + let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0); + if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() { + f.opacity = 0.0; + } + d.node_mut(clear).unwrap().appearance = a.into(); + Ok(()) + }) + .unwrap(); + let kept = [kept, vec![unpainted, clear]].concat(); + let undo = s.doc().unwrap().history.undo.len(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let r = s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left"); + for (k, id) in kept.iter().enumerate() { + assert!(d.node(*id).is_some(), "shape {k} with a width went"); + } + assert_eq!(r["removed"], slivers.len()); + // One undo step brings every sliver back. + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some())); + // A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot. + let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"}); + assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1); + assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some()); +} + +/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or +/// locked slivers. +#[test] +fn select_hairline_slivers_selects_what_clean_up_removes() { + let mut s = session(); + let (slivers, _) = sliver_art(&mut s); + let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z"); + let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(hidden).unwrap().visible = false; + d.node_mut(locked).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert_eq!(r["count"], slivers.len()); + let mut selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + selected.sort_unstable(); + let mut want = slivers.clone(); + want.sort_unstable(); + assert_eq!(selected, want); + // Inside an isolated group, only the slivers in it are selected. + let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z"); + let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z"); + s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + // A sliver in a group is selected as Clean Up finds it. + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1); + assert!(s.doc().unwrap().selection.objects.contains(&inner)); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // A template layer that was unlocked afterward. + let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z"); + s.edit("t", |d, _| { + let n = d.node_mut(template).unwrap(); + if let NodeKind::Layer { template, .. } = &mut n.kind { + *template = true; + } + n.locked = false; + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.node(template).unwrap().is_template()); + s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert!(!s.doc().unwrap().selection.objects.contains(&traced)); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some()); +} + +/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint +/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's +/// clipping path; Clean Up's other options keep the layer's clipping path too. +#[test] +fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() { + let mut s = session(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + s.execute("select.set", &json!({"ids": [rough.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap(); + let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z"); + let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z"); + s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + // A group's own 5 pt stroke draws along its member. + let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z"); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into(); + Ok(()) + }) + .unwrap(); + // A thin part of type's glyph outlines. + let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z"); + s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap(); + let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(outlines).unwrap().extras_mut().type_outlines = true; + Ok(()) + }) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0); + // A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects + // removes the clipping path. + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z"); + let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z"); + let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z"); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went"); + // A clip group whose clipping path is a sliver. + let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z"); + let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z"); + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + // A guide drawn as a sliver, and a sliver with an effect on its stroke. + let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z"); + let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z"); + s.edit("t", |d, _| { + if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind { + *guide = true; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(mask).is_some(), "the clip group's clipping path went"); + assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went"); + // A layer clipped by a group (as an opened file can have it): its sliver member clips too. + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z"); + let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z"); + s.execute("select.set", &json!({"ids": [bare.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind { + *clip = true; + let i = children.iter().position(|c| c.id == g).unwrap(); + let c = children.remove(i); + children.insert(0, c); + } + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went"); +} + +/// A sliver on a locked artboard is left alone. +#[test] +fn hairline_slivers_leave_art_on_a_locked_artboard_alone() { + let mut s = session(); + let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + s.edit("t", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0); + assert!(s.doc().unwrap().doc.node(sliver).is_some()); +} + +/// A sliver at 0 % opacity, and one in a group at 0 % opacity, paint nothing and are left alone. +#[test] +fn hairline_slivers_leave_art_at_zero_opacity_alone() { + let mut s = session(); + let clear = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + let member = filled(&mut s, "M100 10 L140 40 L100.001 10.0015 Z"); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let seen = filled(&mut s, "M200 10 L240 40 L200.001 10.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(clear).unwrap().opacity = 0.0; + d.node_mut(group).unwrap().opacity = 0.0; + d.node_mut(seen).unwrap().opacity = 0.5; + Ok(()) + }) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 1); + let d = &s.doc().unwrap().doc; + assert!(d.node(clear).is_some() && d.node(member).is_some(), "a sliver at 0 % opacity went"); + assert!(d.node(seen).is_none(), "a sliver at 50 % opacity stayed"); +} + +/// A shape too complex to measure is kept, and both commands say how many there were. +#[test] +fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() { + let mut s = session(); + let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + // A closed zigzag of more anchors than one shape is measured with. + let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1; + let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect(); + let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z"); + s.edit("t", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind { + *path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true)); + } + Ok(()) + }) + .unwrap(); + let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}"); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let r = s.execute("object.path.cleanUp", &only).unwrap(); + assert_eq!(r["removed"], 1); + assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(sliver).is_none() && d.node(huge).is_some()); +} + +/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the +/// document, the selection and the undo history stay as they were. +#[test] +fn hairline_slivers_refuse_a_width_out_of_range() { + let mut s = session(); + sliver_art(&mut s); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.selection.objects.clone(), st.history.undo.len()) + }; + let before = state(&s); + for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] { + for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] { + let mut p = serde_json::Map::new(); + p.insert(key.into(), w.clone()); + if cmd == "object.path.cleanUp" { + p.insert("hairlineSlivers".into(), json!(true)); + } + let r = s.execute(cmd, &Value::Object(p)); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}"); + assert!(state(&s) == before, "{cmd} {w} changed the document"); + } + } + // Both ends of the range are taken. + for w in [json!(0.001), json!(3), json!("3 pt")] { + assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}"); + let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w}); + assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}"); + } +} + /// A page-sized square under a ring (a compound path with a square hole), nothing selected. fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) { let art = rect(s, 0.0, 0.0, 100.0, 100.0); diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 635b5f393a..7c4196fd84 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1248,6 +1248,45 @@ fn color_parse_takes_oklch_only_in_an_srgb_working_space() { assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again"); } +/// `color.format` writes `oklch()` only while the working RGB space is sRGB, and writes every CSS +/// form of a CMYK color from the RGB numbers the rendering intent gives, so `color.parse` reads each +/// back to the hex color `color.format` gives. +#[test] +fn color_format_writes_every_css_form_through_the_intent() { + let _g = settings(); + let old = cms::active_settings(); + let mut s = session(); + let format = |s: &mut Session, color: &serde_json::Value, notation: &str| { + s.execute("color.format", &json!({"color": color, "notation": notation})).map(|r| r["text"].as_str().unwrap_or_default().to_string()) + }; + s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let wide = format(&mut s, &json!("#336699"), "oklch").map_err(|e| e.to_string()); + // The Generic CMYK profile's file loaded as an ICC profile, which converts through the intent. + let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name; + s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap(); + let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0}); + let absolute = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8); + let intents_differ = + absolute != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8); + // Collected as results, so that a failure still restores the process-wide settings first. + let mut read_back = vec![]; + for notation in ["hex", "rgb", "hsl", "oklch"] { + let text = format(&mut s, &cyan, notation).map_err(|e| e.to_string()); + let hex = text.clone().and_then(|t| s.execute("color.parse", &json!({"text": t})).map(|r| r["hex"].clone()).map_err(|e| e.to_string())); + read_back.push((notation, text, hex)); + } + cms::set_active(&old).unwrap(); + cms::unregister_icc(&icc); + assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}"); + assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB"); + let hex = read_back[0].1.clone().unwrap(); + let [r, g, b] = absolute; + assert_eq!(hex, format!("#{r:02x}{g:02x}{b:02x}"), "hex is the absolute colorimetric RGB"); + for (notation, text, back) in read_back { + assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}"); + } +} + /// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in /// `Color Settings.json`. #[test] diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index 977c348409..fb529a6733 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -21,7 +21,7 @@ thread_local! { /// The contour passes made over an arrangement on this thread, each of which walks all of it. pub(crate) static CONTOUR_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The sweeps [`normalize_bez`] made on this thread. - static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The input curves [`exact_merge`] tested on this thread. static EXACT_MERGE_CURVES: std::cell::Cell = const { std::cell::Cell::new(0) }; } diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 0ff1b82594..d02e5a8a93 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -15,6 +15,7 @@ mod offset; mod pathfinder; mod planar; mod sweep_axis; +mod thickness; mod trap; pub use boolean::{ @@ -35,6 +36,7 @@ pub use planar::{ Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, }; +pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; /// Errors from fallible operations. diff --git a/crates/pathops/src/thickness.rs b/crates/pathops/src/thickness.rs new file mode 100644 index 0000000000..67771c66a3 --- /dev/null +++ b/crates/pathops/src/thickness.rs @@ -0,0 +1,573 @@ +//! The thickness of a filled shape: whether a circle of a given width fits anywhere inside its +//! fill (Clean Up's and Select › Object's Hairline Slivers). + +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _}; +use vectorcraft_geom::{FillRule, PathData}; + +use crate::boolean::{eps_for, fill_bezpath, normalize_bez}; + +/// Most line pieces the outline of one shape is measured with. +pub const MAX_THICKNESS_PIECES: usize = 100_000; +/// Most cells one search for a wide enough spot looks at. +const MAX_CELLS: usize = 500_000; +/// Most distances from a point to a piece of outline one search measures. +const MAX_WORK: usize = 50_000_000; +/// Most distances from a point to a piece of outline the shapes of one document are measured +/// with, all together ([`ThicknessBudget::document`]). +pub const MAX_DOCUMENT_THICKNESS_WORK: usize = 1_000_000_000; +/// The resolved outline is measured as line pieces within `width / FINE_PARTS` of its curves. +const FINE_PARTS: f64 = 32.0; +/// The first, rough look measures the path as drawn with pieces within `width / ROUGH_PARTS`. +const ROUGH_PARTS: f64 = 8.0; + +/// Is the fill of `path` (every subpath closed, as a fill paints it) under `rule` thinner than +/// `width` everywhere: does no circle of diameter `width` fit inside it? A path with no fill is. +/// A shape within a small fraction of `width` of the limit is taken as thick enough. +/// +/// `None` when it can't be told: `width` isn't a finite positive number, a coordinate isn't +/// finite, the fill can't be resolved into outlines (or only so coarsely, for a shape that large, +/// that edges closer than `width` would merge), or measuring it would take more than +/// [`MAX_THICKNESS_PIECES`] pieces of outline or a search too long. +pub fn thinner_than(path: &PathData, rule: FillRule, width: f64) -> Option { + thinner_than_within(path, rule, width, &mut ThicknessBudget::new(MAX_WORK)) +} + +/// The work left for measuring shapes with [`thinner_than_within`]: a count of distances from a +/// point to a piece of outline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ThicknessBudget(usize); + +impl ThicknessBudget { + pub fn new(work: usize) -> Self { + Self(work) + } + /// The work all the shapes of one document may take: [`MAX_DOCUMENT_THICKNESS_WORK`]. + pub fn document() -> Self { + Self(MAX_DOCUMENT_THICKNESS_WORK) + } + /// The work left. + pub fn left(&self) -> usize { + self.0 + } +} + +/// [`thinner_than`], taking the search's work from `budget`: `None` as well when the search needs +/// more than is left. The quick checks take nothing from it, so they still settle shapes once it +/// runs out. +pub fn thinner_than_within(path: &PathData, rule: FillRule, width: f64, budget: &mut ThicknessBudget) -> Option { + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if !(width.is_finite() && width > 0.0) + || !path.subpaths.iter().flat_map(|sp| &sp.anchors).all(|a| finite(a.p) && finite(a.h_in) && finite(a.h_out)) + { + return None; + } + // Every segment is at least one piece of outline, so a path of more anchors is too long to + // measure before its outline is built. + if path.subpaths.iter().map(|sp| sp.anchors.len()).sum::() > MAX_THICKNESS_PIECES { + return None; + } + let mut bp = fill_bezpath(path); + if bp.elements().is_empty() { + return Some(true); + } + // Measured from the corner of its bounds, so that a shape far from the origin measures as it + // does near it. + let corner = bp.bounding_box().origin(); + bp.apply_affine(Affine::translate(-corner.to_vec2())); + let b = bp.bounding_box(); + let (r, fine) = (width / 2.0, width / FINE_PARTS); + // A circle inside the fill is inside its bounds. Bounds within the fine measure's error of the + // width go on to that measure, which keeps them. + if b.width().min(b.height()) < width - 2.0 * fine { + return Some(true); + } + // Every point of a fill lies within the widest circle's radius r of its outline, and the points + // within r of a closed outline of length L cover at most 2rL + πr². A fill larger than that holds + // a circle of diameter `width`. Only one subpath filled nonzero that winds at most once around + // any point is measured so: the areas of several subpaths add up to more than their fill where + // they overlap, a path that runs around a spot twice counts its area there twice, and an + // even-odd fill of a path that runs around twice is empty. + if path.subpaths.len() == 1 + && rule == FillRule::NonZero + && winds_at_most_once(&bp) + && bp.area().abs() > 2.0 * r * bp.perimeter(1e-3) * 1.01 + std::f64::consts::PI * r * r + { + return Some(false); + } + // The circle lies between any two parallel lines that hold the path's points and handles too, + // which settles a long sliver lying on a slant. + if hull_width(&bp) < width - 2.0 * fine { + return Some(true); + } + // A rough look at the path as drawn: an edge running inside the fill is nearer than the fill's + // outline, so a spot this far from every edge (and from the rough pieces' error) is far enough. + let rough = width / ROUGH_PARTS; + let mut edges = vec![]; + if !flatten_into(&bp, rough, &mut edges) { + return None; + } + match search(&edges, b, rule, r + rough, rough, budget) { + Search::Found => return Some(false), + // Resolving the outlines takes time of its own, so it isn't started when what is left of + // the budget cut the rough look short. The rough look can run out where the resolved + // outline is much shorter, so one that ran out of its own share goes on. + Search::TooLong if budget.0 < MAX_WORK => return None, + _ => {} + } + // The fill's own outlines: where subpaths overlap or a path crosses itself, the edges inside the + // fill are no outline of it. A spot within the fine pieces' error of the radius counts as one. + // The sweep snaps points within its tolerance together, which grows with the shape's size: one + // as coarse as the fine pieces could close up a fill that holds the circle, so it isn't measured. + if eps_for([&bp]).ok()? >= fine { + return None; + } + let contours = normalize_bez(&bp, rule).ok()?; + edges.clear(); + for c in contours.contours() { + if !flatten_into(&c.path, fine, &mut edges) { + return None; + } + } + if edges.is_empty() { + return Some(true); + } + match search(&edges, b, FillRule::EvenOdd, r - fine, fine, budget) { + Search::Found | Search::Unsure => Some(false), + Search::Absent => Some(true), + Search::TooLong => None, + } +} + +/// The points and handles of `bp`, in order. +fn control_points(bp: &BezPath) -> Vec { + bp.elements() + .iter() + .flat_map(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p], + PathEl::QuadTo(a, p) => vec![a, p], + PathEl::CurveTo(a, b, p) => vec![a, b, p], + PathEl::ClosePath => vec![], + }) + .collect() +} + +/// Does `bp`, one closed subpath, wind at most once around every point? Every line through a point +/// that a curve winds around twice crosses it at least four times, so such a curve turns through +/// at least 4π in all. A Bézier curve turns no more than its control polygon, so a control polygon +/// that turns through less than 4π winds at most once. +fn winds_at_most_once(bp: &BezPath) -> bool { + let mut pts = control_points(bp); + pts.dedup(); + while pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + if pts.len() < 3 { + return true; + } + let turned: f64 = pts + .iter() + .zip(pts.iter().cycle().skip(1)) + .zip(pts.iter().cycle().skip(2)) + .map(|((&a, &b), &c)| { + let (u, v) = (b - a, c - b); + u.cross(v).atan2(u.dot(v)).abs() + }) + .sum(); + turned < 4.0 * std::f64::consts::PI * (1.0 - 1e-9) +} + +/// Most corners of a convex hull [`hull_width`] measures; a larger hull measures as unbounded. +const MAX_HULL: usize = 512; + +/// The least distance between two parallel lines that hold every point and handle of `bp` (the +/// width of their convex hull, which holds the curves too). +fn hull_width(bp: &BezPath) -> f64 { + let mut pts = control_points(bp); + pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + pts.dedup(); + if pts.len() < 3 { + return 0.0; + } + // Andrew's monotone chain: the lower hull, then the upper. + let turn = |o: Point, a: Point, b: Point| (a - o).cross(b - o); + let mut hull: Vec = Vec::with_capacity(pts.len() + 1); + for pass in [false, true] { + let floor = hull.len(); + let ordered: Box> = if pass { Box::new(pts.iter().rev()) } else { Box::new(pts.iter()) }; + for &p in ordered { + while hull.len() >= floor + 2 && hull.get(hull.len() - 2).zip(hull.last()).is_some_and(|(&o, &a)| turn(o, a, p) <= 0.0) { + hull.pop(); + } + hull.push(p); + } + hull.pop(); + } + if hull.len() < 3 { + return 0.0; + } + if hull.len() > MAX_HULL { + return f64::INFINITY; + } + // For each side, the farthest corner from its line; the least of those is the width. + let mut least = f64::INFINITY; + for (&a, &b) in hull.iter().zip(hull.iter().cycle().skip(1)) { + let side = b - a; + let len = side.hypot(); + if len > 0.0 { + let far = hull.iter().map(|&p| side.cross(p - a).abs() / len).fold(0.0, f64::max); + least = least.min(far); + } + } + least +} + +/// Add `bp`'s outline to `edges` as line pieces within `tolerance` of it: false when that takes +/// more than [`MAX_THICKNESS_PIECES`], or when a curve is too long for [`vectorcraft_geom::flatten`] +/// to keep within `tolerance`. +fn flatten_into(bp: &BezPath, tolerance: f64, edges: &mut Vec<(Point, Point)>) -> bool { + let push = |from: Point, to: Point, edges: &mut Vec<(Point, Point)>| { + if from != to { + edges.push((from, to)); + } + }; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + let most = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE; + for el in bp.iter() { + if edges.len() > MAX_THICKNESS_PIECES { + return false; + } + match el { + // An outline that doesn't end where it starts is closed with a line, as a fill paints it. + PathEl::MoveTo(p) => { + push(last, start, edges); + (start, last) = (p, p); + } + PathEl::ClosePath => { + push(last, start, edges); + last = start; + } + PathEl::LineTo(p) => { + push(last, p, edges); + last = p; + } + PathEl::QuadTo(a, p) | PathEl::CurveTo(a, _, p) => { + let length = match el { + PathEl::CurveTo(_, b, _) => last.distance(a) + a.distance(b) + b.distance(p), + _ => last.distance(a) + a.distance(p), + }; + if length / most > tolerance { + return false; + } + let mut from = last; + vectorcraft_geom::flatten([PathEl::MoveTo(last), el], tolerance, |piece| { + if let PathEl::LineTo(to) = piece { + push(from, to, edges); + from = to; + } + }); + last = p; + } + } + } + push(last, start, edges); + edges.len() <= MAX_THICKNESS_PIECES +} + +/// The distance from `p` to the nearest of `edges`, negative outside the region they bound under +/// `rule`. +fn signed_distance(edges: &[(Point, Point)], rule: FillRule, p: Point) -> f64 { + let mut winding = 0i32; + let mut nearest = f64::INFINITY; + for &(a, b) in edges { + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { + winding += if b.y > a.y { 1 } else { -1 }; + } + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + nearest = nearest.min((p - (a + ab * t)).hypot2()); + } + let inside = match rule { + FillRule::NonZero => winding != 0, + FillRule::EvenOdd => winding % 2 != 0, + }; + let d = nearest.sqrt(); + if inside { d } else { -d } +} + +/// A square cell of the search: its center, half its side, the signed distance from its center to +/// the outline, and the most that distance can be anywhere in it. +struct Cell { + c: Point, + h: f64, + d: f64, + most: f64, +} + +impl PartialEq for Cell { + fn eq(&self, other: &Self) -> bool { + self.most.total_cmp(&other.most) == Ordering::Equal + } +} + +impl Eq for Cell {} + +impl PartialOrd for Cell { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Cell { + fn cmp(&self, other: &Self) -> Ordering { + self.most.total_cmp(&other.most) + } +} + +/// What [`search`] found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Search { + /// A point at least the distance asked for from the outline. + Found, + /// No such point. + Absent, + /// None found, but cells smaller than the finest size could still hold one. + Unsure, + /// The search needed more cells or distances than it may take. + TooLong, +} + +/// Look for a point inside the region `edges` bound under `rule` (within `bounds`) at least `goal` +/// from its outline. The bounds are cut into square cells, and the cell that could hold the farthest +/// point is split first, until a cell's center is `goal` away or no cell could be. The distance +/// changes no faster than the point moves, so a cell holds no point farther than its center's +/// distance plus half its diagonal. Cells smaller than `finest` are not split further. The +/// distances it measures, no more than [`MAX_WORK`], are taken from `budget`. +fn search(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, goal: f64, finest: f64, budget: &mut ThicknessBudget) -> Search { + let mut work = 0usize; + let found = search_up_to(edges, bounds, rule, (goal, finest), budget.0.min(MAX_WORK), &mut work); + budget.0 = budget.0.saturating_sub(work); + found +} + +/// [`search`], measuring no more than `limit` distances and counting them in `work`. +fn search_up_to(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, (goal, finest): (f64, f64), limit: usize, work: &mut usize) -> Search { + let side = bounds.width().min(bounds.height()); + if side.is_nan() || side <= 0.0 { + return Search::Absent; + } + let (cols, rows) = ((bounds.width() / side).ceil(), (bounds.height() / side).ceil()); + if cols * rows > MAX_CELLS as f64 || cols * rows * edges.len() as f64 > limit as f64 { + return Search::TooLong; + } + let cell = |c: Point, h: f64, work: &mut usize| { + *work += edges.len(); + let d = signed_distance(edges, rule, c); + Cell { c, h, d, most: d + h * std::f64::consts::SQRT_2 } + }; + let mut heap = BinaryHeap::new(); + let h = side / 2.0; + for i in 0..cols as usize { + for j in 0..rows as usize { + heap.push(cell(Point::new(bounds.x0 + (i as f64 + 0.5) * side, bounds.y0 + (j as f64 + 0.5) * side), h, work)); + } + } + let (mut made, mut unsure) = (heap.len(), false); + while let Some(next) = heap.pop() { + if next.d >= goal { + return Search::Found; + } + if next.most < goal { + break; + } + if next.h < finest / 2.0 { + unsure = true; + continue; + } + if made + 4 > MAX_CELLS || work.saturating_add(4 * edges.len()) > limit { + return Search::TooLong; + } + let h = next.h / 2.0; + for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] { + let part = cell(Point::new(next.c.x + dx, next.c.y + dy), h, work); + // A cell that can't hold a point `goal` away is left out. + if part.most >= goal { + heap.push(part); + } + } + made += 4; + } + if unsure { Search::Unsure } else { Search::Absent } +} + +#[cfg(test)] +mod tests { + use vectorcraft_geom::{Anchor, SubPath}; + + use super::*; + + fn polygon(points: &[(f64, f64)]) -> SubPath { + SubPath::new(points.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true) + } + + fn one(points: &[(f64, f64)]) -> PathData { + PathData::single(polygon(points)) + } + + fn thin(p: &PathData, rule: FillRule, width: f64) -> bool { + thinner_than(p, rule, width) == Some(true) + } + + fn thick(p: &PathData, rule: FillRule, width: f64) -> bool { + thinner_than(p, rule, width) == Some(false) + } + + #[test] + fn a_triangle_whose_third_anchor_almost_meets_its_first_is_thinner_than_a_hairline() { + let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]); + assert!(thin(&sliver, FillRule::NonZero, 0.085)); + // Long and on a slant at the narrowest width, and far from the origin. + assert!(thin(&one(&[(0.0, 0.0), (600.0, 600.0), (0.0, 0.0001)]), FillRule::NonZero, 0.001)); + let (x, y) = (1_000_000.0, 1_000_000.0); + assert!(thin(&one(&[(x, y), (x + 0.01, y + 0.0075), (x + 0.0001, y + 0.0002)]), FillRule::NonZero, 0.001)); + } + + #[test] + fn a_bent_sliver_is_found_by_measuring_inside_it() { + // Out along two sides of a triangle and back 0.002 pt inside them: its hull and bounds are + // wide, and only the measure inside finds it thin. + let v = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]); + assert!(thin(&v, FillRule::NonZero, 0.085)); + } + + #[test] + fn a_narrow_strip_wider_than_the_width_is_kept_and_one_narrower_is_not() { + // A diagonal strip 100 pt long. + let strip = |w: f64| { + let (dx, dy) = (0.6 * w, -0.8 * w); + one(&[(0.0, 0.0), (80.0, 60.0), (80.0 + dx, 60.0 + dy), (dx, dy)]) + }; + assert!(thick(&strip(0.2), FillRule::NonZero, 0.085)); + assert!(thick(&strip(0.2), FillRule::NonZero, 0.18)); + assert!(thin(&strip(0.05), FillRule::NonZero, 0.085)); + assert!(thin(&strip(0.2), FillRule::NonZero, 0.24)); + } + + #[test] + fn a_triangle_holding_the_circle_off_every_cell_center_is_kept() { + // Its inscribed circle is 2 across, centered at (1, 1). + let t = one(&[(0.0, 0.0), (4.0, 0.0), (0.0, 3.0)]); + assert!(thick(&t, FillRule::NonZero, 1.95)); + assert!(thin(&t, FillRule::NonZero, 2.3)); + } + + #[test] + fn a_tiny_round_dot_is_kept() { + let dot = vectorcraft_geom::shapes::ellipse(kurbo::Rect::new(10.0, 10.0, 10.3, 10.3)); + assert!(thick(&dot, FillRule::NonZero, 0.085)); + assert!(thick(&dot, FillRule::NonZero, 0.29)); + assert!(thin(&dot, FillRule::NonZero, 0.4)); + } + + #[test] + fn a_thin_ring_is_thin_whichever_way_its_subpaths_run() { + let square = |x0: f64, x1: f64| polygon(&[(x0, x0), (x1, x0), (x1, x1), (x0, x1)]); + let mut hole = square(1.01, 98.99); + hole.reverse(); + assert!(thin(&PathData::new(vec![square(1.0, 99.0), hole]), FillRule::NonZero, 0.085)); + // Even-odd: an inner square running the same way still cuts a hole. + assert!(thin(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::EvenOdd, 0.085)); + // Nonzero: it doesn't, and the edges inside the fill are no outline of it. + assert!(thick(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::NonZero, 0.085)); + } + + #[test] + fn overlapping_strips_are_measured_by_their_union() { + // Two strips 0.2 pt tall overlapping by half: their fill is 0.3 pt tall, while the edges of + // each that run inside the other are no more than 0.1 pt apart. + let strip = |y: f64| polygon(&[(0.0, y), (100.0, y), (100.0, y + 0.2), (0.0, y + 0.2)]); + let strips = PathData::new(vec![strip(0.0), strip(0.1)]); + assert!(thick(&strips, FillRule::NonZero, 0.15)); + assert!(thin(&strips, FillRule::NonZero, 0.35)); + } + + #[test] + fn an_outline_out_and_back_along_itself_has_no_fill_and_is_thin() { + assert!(thin(&one(&[(0.0, 0.0), (30.0, 40.0), (0.0, 0.0), (30.0, 40.0)]), FillRule::NonZero, 0.085)); + assert!(thin(&PathData::default(), FillRule::NonZero, 0.085)); + } + + /// Shapes thicker than the width by their area, and slivers lying flat along an axis, are settled + /// without resolving their outlines, so a document of thousands of them is measured quickly. + #[test] + fn plain_shapes_and_flat_slivers_are_settled_without_resolving_their_outlines() { + let before = crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()); + for k in 0..2000 { + let x = f64::from(k) * 12.0; + assert!(thick(&one(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0), (x, 10.0)]), FillRule::NonZero, 0.085)); + assert!(thin(&one(&[(x, 20.0), (x + 10.0, 20.0), (x + 10.0, 20.01), (x, 20.01)]), FillRule::NonZero, 0.085)); + // Long slivers on a slant are settled by the width of their hull. + assert!(thin(&one(&[(x, 40.0), (x + 9.0, 52.0), (x + 0.001, 40.0015)]), FillRule::NonZero, 0.085)); + } + assert_eq!(crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()), before); + } + + /// The area measure is used only for an outline that runs around once: one that runs around + /// twice counts its area twice. + #[test] + fn an_outline_that_runs_around_twice_is_not_measured_by_its_area() { + let square = |n: usize| { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for _ in 0..n { + for p in [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] { + bp.line_to(p); + } + } + bp.close_path(); + bp + }; + assert!(winds_at_most_once(&square(1))); + assert!(!winds_at_most_once(&square(2))); + // Measured inside instead, a square run around twice is still as thick as one. + let twice = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + assert!(thick(&twice, FillRule::NonZero, 0.085)); + } + + /// Shapes that need the search share one budget: once it is spent they can't be measured, and + /// the quick checks still settle the rest. + #[test] + fn a_spent_budget_leaves_the_shapes_that_need_a_search_unmeasured() { + let bent = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]); + let square = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let mut budget = ThicknessBudget::document(); + assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut budget), Some(true)); + assert!(budget.left() < MAX_DOCUMENT_THICKNESS_WORK); + let mut spent = ThicknessBudget::new(0); + assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut spent), None); + assert_eq!(thinner_than_within(&square, FillRule::NonZero, 0.085, &mut spent), Some(false)); + } + + /// A shape so long that resolving its outline snaps edges closer than the width together is not + /// measured, while the same height at an ordinary length is. + #[test] + fn a_shape_too_long_to_resolve_at_the_width_cannot_be_measured() { + let rect = |w: f64| one(&[(0.0, 0.0), (w, 0.0), (w, 0.0011), (0.0, 0.0011)]); + assert_eq!(thinner_than(&rect(1e12), FillRule::NonZero, 0.001), None); + assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.001), Some(false)); + assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.0012), Some(true)); + } + + #[test] + fn a_width_or_a_coordinate_that_is_no_finite_number_cannot_be_measured() { + let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]); + for w in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert_eq!(thinner_than(&sliver, FillRule::NonZero, w), None, "{w}"); + } + let flat = one(&[(0.0, 0.0), (f64::NAN, 0.0), (40.0, 0.0)]); + assert_eq!(thinner_than(&flat, FillRule::NonZero, 0.085), None); + } +} diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 0e331057d7..b7156550c8 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -65,6 +65,11 @@ impl Known { self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure) } + /// No variable holds a member chain or a File or Folder object. [`Known::unsure`] may be set. + pub fn no_names(&self) -> bool { + self.bound.is_empty() && self.files.is_empty() + } + /// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already /// bound keeps its chain. A name that holds a File or Folder object on both sides holds a Folder /// object only when both sides say so; otherwise it may hold a File object. diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index e74d299aaa..9075c53517 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -231,7 +231,9 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits: /// that includes nothing, so a variable a function uses before the global code assigns it holds /// what it is assigned. `first` holds the scan made with nothing known, which found `known`, and /// `pre` what came before it. A scan made with what the scans before it found, and that finds -/// nothing more, is the report scan; no other scan is repeated. +/// nothing more, is the report scan; no other scan is repeated. When `known` holds no name, `first` +/// is the report: [`analyze::Known::unsure`] alone comes from `declared`, which the first scan +/// already read. fn settle<'l>( first: report::Acc<'l>, pre: report::Acc<'l>, @@ -240,7 +242,7 @@ fn settle<'l>( braced: &[analyze::Braced], mut known: analyze::Known, ) -> report::Acc<'l> { - if known.len() == 0 { + if known.no_names() { return first; } let entries = pre.limits.entries; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 0d65836ef6..af88ac8fa7 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1935,12 +1935,41 @@ fn the_costliest_inputs_stay_within_five_steps_a_byte() { format!("\\u0061;function f({}) {{ var {}; }}", names.join(","), names.join(",")), format!("\\u0061;function f({}) {{}}", vec!["a"; 900].join(",")), format!("\\u0061;{}", "x=(".repeat(600)), + format!("\\u0061;o[k];{}", "{".repeat(2_000)), ] { let r = report(&src); assert!(r.steps <= 5 * src.len() + 16, "{} steps for {} bytes", r.steps, src.len()); } } +/// The most steps a check of `bytes` without a loader may take. The text is read once for the +/// escapes and once for the names declared, and a scan takes at most three steps a byte. A script +/// whose variables hold nothing the check follows is scanned once: five steps a byte. Any other +/// script is scanned up to five times (the first scan, three more while what its variables hold +/// grows, and the report's): seventeen steps a byte. +fn step_bound(bytes: &[u8]) -> usize { + let limits = Limits::default(); + let mut acc = report::Acc::new(&limits); + let (text, _) = decode(bytes); + let (text, braced) = analyze::unescaped(text, &mut acc); + let declared = analyze::declarations(&text, &mut acc); + let known = analyze::scan(&text, &declared, &braced, None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc).known; + let scans = if known.no_names() { 1 } else { 5 }; + (2 + 3 * scans) * bytes.len() + 16 +} + +/// A name in brackets that is not one literal (`0[ \| … ]`) gives no variable a value, so the +/// script is scanned once. The bytes are the ones a run of the property below found. +#[test] +fn a_script_that_binds_no_name_is_scanned_once() { + let bytes: &[u8] = b"\x01\x01 \x010 !0!\x01!\x01#\x01#{#{ 0( #0\x01( \x01( {#{ # \x01#0:((0[\t \\| \x1b!!0:|!| 0) ) )] ! \x1b \x1b \x1b \\u\t\x01"; + assert_eq!(bytes.len(), 104); + let r = check("a.jsx", bytes, None, &Limits::default()); + assert_eq!(r.kind, Kind::Script); + assert_eq!(step_bound(bytes), 5 * bytes.len() + 16); + assert!(r.steps <= 5 * bytes.len() + 16, "{} steps for {} bytes", r.steps, bytes.len()); +} + #[test] fn lists_stop_at_their_limits_and_echoes_are_cut() { let mut s = String::new(); @@ -2339,13 +2368,13 @@ proptest! { #[test] fn any_bytes_are_checked_in_linear_work(bytes in prop::collection::vec(any::(), 0..2_000), jsxbin in any::()) { let r = check(if jsxbin { "a.jsxbin" } else { "a.jsx" }, &bytes, None, &Limits::default()); - prop_assert!(r.steps <= 5 * bytes.len() + 16, "{} steps for {} bytes", r.steps, bytes.len()); + prop_assert!(r.steps <= step_bound(&bytes), "{} steps for {} bytes", r.steps, bytes.len()); } #[test] fn script_like_text_is_checked_in_linear_work(text in script_text()) { let r = report(&text); - prop_assert!(r.steps <= 5 * text.len() + 16, "{} steps for {} bytes", r.steps, text.len()); + prop_assert!(r.steps <= step_bound(text.as_bytes()), "{} steps for {} bytes", r.steps, text.len()); let limits = Limits::default(); for list in [r.targets.len(), r.directives.len(), r.includes.len(), r.members.len(), r.types.len(), r.menu_strings.len(), r.problems.len()] { prop_assert!(list <= limits.entries); diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index c15a150d31..1200db46de 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -120,9 +120,11 @@ pub(crate) struct CanvasDrops<'a> { kind: BodyKind, /// The uid of the document the canvas shows. document: u64, - /// The revert count of the document the canvas shows: an appearance dragged from contents File › Revert replaced is - /// refused. + /// The revert count of the document the canvas shows: an appearance, graphic style or brush dragged from contents + /// File › Revert replaced is refused. reverts: u64, + /// `(uid, reverts)` of every open document: a symbol dragged from contents File › Revert replaced is refused. + contents: Vec<(u64, u64)>, /// `(uid, revision)` of every open document: carried art whose source is not listed unchanged is refused. sources: Vec<(u64, u64)>, /// Whether the art being carried is taken though its source's revision moved: its move was given up and the source @@ -176,12 +178,17 @@ impl Component for CanvasDrops<'_> { let panel = Target::new(rect, view, covered, |p: &PanelDrag| match p { PanelDrag::Art { .. } => None, PanelDrag::Appearance { .. } if p.appearance_for(self.document, self.reverts).is_none() => None, + _ if p.stale_rows(Some((self.document, self.reverts))) => None, _ => Some(Payload::Panel(p.clone())), }); - let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); - let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); + let here = (self.document, self.reverts); + let style = Target::new(rect, view, covered, |d: &StyleDrag| ((d.document, d.reverts) == here).then(|| Payload::Style(d.clone()))); + // A symbol of any open document's current contents. + let symbol = Target::new(rect, view, covered, |d: &ListDrag| { + self.contents.contains(&(d.grabbed.doc, d.grabbed.reverts)).then(|| Payload::Symbol(d.grabbed.clone())) + }); let brush = Target::new(rect, view, covered, |d: &ListDrag| { - (d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone())) + ((d.grabbed.doc, d.grabbed.reverts) == here).then(|| Payload::Brush(d.grabbed.clone())) }); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); @@ -222,6 +229,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi BodyKind::Pane => pane_view(app, win, rect), }; let (Some(view), Some((document, reverts))) = (view, app.session.documents().get(win.0).map(|d| (d.uid, d.reverts))) else { return }; + let contents = app.session.documents().iter().map(|d| (d.uid, d.reverts)).collect(); let sources = app.session.documents().iter().map(|d| (d.uid, d.revision)).chain(app.canvas.panes.released_from).collect(); // A tab rest leaves the art to the document it showed while that is the current one: any canvas or pane takes it // then, and nothing once that document was closed or left by other means. @@ -234,7 +242,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi let ctx = ui.ctx().clone(); let covered = |at: Pos2| crate::panel_docking::os_window_at(app, &ctx, at); let files = (CanvasFiles::new(app, rect, &view), &files_out); - let drops = CanvasDrops { common: Common::new(), view, kind, document, reverts, sources, given_up, covered: &covered, out: &out, files }; + let drops = + CanvasDrops { common: Common::new(), view, kind, document, reverts, contents, sources, given_up, covered: &covered, out: &out, files }; drops.id_salt(("canvas-drops", win)).show_at(ui, rect); if let Some(files) = files_out.take() { crate::place::canvas_drop(app, ui.ctx(), files); @@ -330,6 +339,8 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), ) } } + // A symbol of contents File › Revert replaced places nothing. + Payload::Symbol(key) if !app.session.documents().iter().any(|d| (d.uid, d.reverts) == (key.doc, key.reverts)) => Ok(()), Payload::Symbol(key) => run(app, "symbol.placeFromDocument", json!({"sourceDocument": key.doc, "name": key.name, "x": at.x, "y": at.y})), Payload::Library(key) if key.folder => Ok(()), Payload::Library(key) => match library_panel::parse(&key.panel) { @@ -346,7 +357,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => { run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]})) } - Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() { + Payload::Brush(key) if app.session.active().is_some_and(|st| (st.uid, st.reverts) == (key.doc, key.reverts)) => match hit() { None if brush_has_art(app, key) && no_art_at(app, at, zoom) => { run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})) } @@ -357,12 +368,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), } }, Payload::Brush(_) => Ok(()), - Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => { + Payload::Style(style) if app.session.active().is_some_and(|st| (st.uid, st.reverts) == (style.document, style.reverts)) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } Payload::Style(_) => Ok(()), + // Swatch rows of contents File › Revert replaced apply and place nothing. + Payload::Panel(drag @ PanelDrag::Paint { .. }) if drag.stale_rows(app.session.active().map(|st| (st.uid, st.reverts))) => Ok(()), // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile art with its tile. Payload::Panel(PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) if hit().is_none() && no_art_at(app, at, zoom) => @@ -385,7 +398,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), { return Err(tl!("A linked color swatch can only be applied in its own document.").into()); } - let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) }; + let Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| (st.uid, st.reverts))) else { return Ok(()) }; params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 802568a10a..4e7b5a71c8 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -68,7 +68,7 @@ fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() { let before = fill(&app); let history = undo_len(&app); let at = Point::new(250.0, 70.0); - let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() }); + let payload = Payload::Style(StyleDrag { document, reverts: 0, name: "Shared name".into() }); for operation in [DropOperation::Move, DropOperation::Copy] { drop_at(&mut app, payload.clone(), at, operation).unwrap(); assert_eq!(fill(&app), before); @@ -135,7 +135,7 @@ fn a_drop_runs_the_effect_of_its_payload() { assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays"); let st = app.session.active().unwrap(); let name = st.doc.graphic_styles[2].name.clone(); - let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() }); + let style = Payload::Style(StyleDrag { document: st.uid, reverts: st.reverts, name: name.clone() }); drop_at(&mut app, style.clone(), on_b, Move).unwrap(); let st = app.session.active().unwrap(); assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id)); @@ -165,7 +165,7 @@ fn a_drop_runs_the_effect_of_its_payload() { let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap()); let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone()); let uid = app.session.active().unwrap().uid; - let brush = |name: &str| Payload::Brush(BrushKey { doc: uid, name: name.into(), group: false }); + let brush = |name: &str| Payload::Brush(BrushKey { doc: uid, reverts: 0, name: name.into(), group: false }); let library = |kind: &str, id: &str, name: &str| { Payload::Library(LibraryKey { panel: library_panel::panel_id(kind, id), name: name.into(), folder: false }) }; @@ -200,7 +200,7 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, library(SymbolLibraries::KIND, "basic-shapes", "Star"), on_b, Move).unwrap(); assert_eq!(undo_len(&app), n + 1, "a library symbol is added and placed in one step"); symbol_at(&app, on_b); - drop_at(&mut app, Payload::Symbol(SymbolKey { doc: uid, name: "Star".into() }), empty, Move).unwrap(); + drop_at(&mut app, Payload::Symbol(SymbolKey { doc: uid, reverts: 0, name: "Star".into() }), empty, Move).unwrap(); symbol_at(&app, empty); } @@ -215,8 +215,13 @@ fn a_brush_with_art_dropped_inside_a_fill_with_path_only_places_nothing() { app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); let uid = app.session.active().unwrap().uid; let n = undo_len(&app); - drop_at(&mut app, Payload::Brush(BrushKey { doc: uid, name: "Arrow".into(), group: false }), Point::new(300.0, 240.0), DropOperation::Move) - .unwrap(); + drop_at( + &mut app, + Payload::Brush(BrushKey { doc: uid, reverts: 0, name: "Arrow".into(), group: false }), + Point::new(300.0, 240.0), + DropOperation::Move, + ) + .unwrap(); assert_eq!(undo_len(&app), n, "{}", app.ui.status); } @@ -235,6 +240,7 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { let swatch = |name: &str, paint: Paint| { let rows = SwatchRows { document, + reverts: 0, grabbed: name.into(), names: vec![name.into()], groups: false, @@ -288,7 +294,7 @@ fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() { let before = brush_of(&app); assert!(before.is_none()); let history = undo_len(&app); - let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false }); + let payload = Payload::Brush(BrushKey { doc: document, reverts: 0, name: "Shared Brush".into(), group: false }); drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap(); assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone"); drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap(); @@ -308,7 +314,7 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = crate::testing::ui_context(); frame(&mut app, &ctx, vec![]); - let key = |doc| Payload::Symbol(SymbolKey { doc, name: "Leaf".into() }); + let key = |doc| Payload::Symbol(SymbolKey { doc, reverts: 0, name: "Leaf".into() }); let at = Point::new(250.0, 180.0); let n = undo_len(&app); drop_at(&mut app, key(source), at, DropOperation::Move).unwrap(); @@ -338,6 +344,7 @@ fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() { let paint = source.doc.swatch(name).unwrap().paint.clone(); let rows = SwatchRows { document: source.uid, + reverts: source.reverts, grabbed: name.into(), names: vec![name.into()], groups: false, @@ -734,3 +741,82 @@ fn an_appearance_drop_after_file_revert_leaves_the_restored_object_unchanged() { panel.release(); assert_eq!(fill(&panel.app()), red, "a drag started after the revert copies the appearance"); } + +/// A graphic style, brush or symbol held across File › Revert, released on art on the canvas, makes no edit to the +/// restored contents, both where the canvas takes the drop and where the drop is applied. The same drag started after +/// the revert still applies or places it. +#[test] +fn a_style_brush_or_symbol_held_across_file_revert_is_not_dropped_on_the_canvas() { + use crate::tests::panel_harness::Panel; + use craft::ui::runtime::drag; + + fn beside_canvas(app: &mut VectorcraftApp, ui: &mut egui::Ui, panel: fn(&mut VectorcraftApp, &mut egui::Ui)) { + app.sync_views(); + egui::Panel::top("source panel").exact_size(220.0).show(ui, |ui| panel(app, ui)); + canvas::show(app, ui); + } + fn styles(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + beside_canvas(app, ui, crate::panels::graphic_styles::show); + } + fn brushes(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + beside_canvas(app, ui, crate::panels::brushes::show); + } + fn symbols(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + beside_canvas(app, ui, crate::panels::symbols::show); + } + + type Show = fn(&mut VectorcraftApp, &mut egui::Ui); + let panels: [(&str, Show); 3] = [("style", styles), ("brush", brushes), ("symbol", symbols)]; + for (kind, show) in panels { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap(); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + match kind { + "style" => app.run("graphicStyle.new", json!({"name": "Held"})).map(drop), + "brush" => app + .run("brush.new", json!({"name": "Held", "type": "art"})) + .and_then(|_| app.run("brush.setCurrent", json!({"name": null})).map(drop)), + _ => app.run("symbol.new", json!({"name": "Held"})).map(drop), + } + .unwrap(); + app.run("path.create", json!({"anchors": [{"x": 200, "y": 150}, {"x": 380, "y": 150}]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("canvas-panel-item-drop-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.ellipse", json!({"x": 20, "y": 250, "width": 20, "height": 20})).unwrap(); + app.run("select.none", json!({})).unwrap(); + + let mut panel = Panel::new(app, show); + let hold = |panel: &mut Panel| { + let from = panel.rect("Held").center(); + let to = panel.app().canvas_view().unwrap().to_screen(Point::new(290.0, 150.0)); + panel.drag_hold_between(from, to); + }; + hold(&mut panel); + assert!(drag::mark(panel.ctx()).is_some(), "{kind}: the canvas takes it from the current contents"); + let opening = panel.app().session.active().map(|st| (st.uid, st.reverts)).unwrap(); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.frame(); + assert_eq!(panel.app().session.active().map(|st| (st.uid, st.reverts)), Some((opening.0, opening.1 + 1))); + let history = undo_len(&panel.app()); + assert!(drag::mark(panel.ctx()).is_none(), "{kind}: the canvas refuses it once the contents it came from are gone"); + panel.release(); + assert_eq!(undo_len(&panel.app()), history, "{kind}: the stale drop makes no edit"); + + let stale = match kind { + "style" => Payload::Style(StyleDrag { document: opening.0, reverts: opening.1, name: "Held".into() }), + "brush" => Payload::Brush(BrushKey { doc: opening.0, reverts: opening.1, name: "Held".into(), group: false }), + _ => Payload::Symbol(SymbolKey { doc: opening.0, reverts: opening.1, name: "Held".into() }), + }; + drop_at(&mut panel.app(), stale, Point::new(290.0, 150.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(&panel.app()), history, "{kind}: a stale payload that reaches the drop is not applied"); + + hold(&mut panel); + panel.release(); + assert_eq!(undo_len(&panel.app()), history + 1, "{kind}: a drag started after the revert is still dropped"); + } +} diff --git a/crates/ui-egui/src/canvas/rulers.rs b/crates/ui-egui/src/canvas/rulers.rs index 34a6a223b9..a72e55995f 100644 --- a/crates/ui-egui/src/canvas/rulers.rs +++ b/crates/ui-egui/src/canvas/rulers.rs @@ -62,7 +62,7 @@ pub(crate) fn units() -> &'static [UnitKind] { } /// Lengths stored in points and shown in `unit`, a bare number read as Numbers Without Units Are Points says. -fn lengths(app: &VectorcraftApp, unit: Unit) -> LengthUnits { +pub(crate) fn lengths(app: &VectorcraftApp, unit: Unit) -> LengthUnits { crate::fields::bare_points( LengthUnits::new(UnitKind::Points, unit_kind(unit), PIXELS_PER_INCH), app.session.prefs.numbers_without_units_are_points, diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 92f19cb4a8..6d8741d342 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -59,6 +59,9 @@ struct Open { struct Setting { cmyk: bool, units: LengthUnits, + /// Hairline Slivers' widths: the stroke unit (Preferences › Units › Stroke), or points when + /// that unit's field rounds the narrowest width to 0. + sliver_units: LengthUnits, } impl Setting { @@ -67,8 +70,23 @@ impl Setting { cmyk: app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk), // PLAN: assumed `canvas::rulers::general_lengths(&VectorcraftApp) -> LengthUnits` (cv.B5) units: crate::canvas::rulers::general_lengths(app), + sliver_units: crate::canvas::rulers::lengths(app, sliver_unit(app.session.stroke_unit())), } } + + /// The length units of `command`'s distance rows. + fn units_for(self, command: &str) -> LengthUnits { + match command { + "object.path.cleanUp" | "select.object.hairlineSlivers" => self.sliver_units, + _ => self.units, + } + } +} + +/// The unit Hairline Slivers' widths show in for the stroke unit `stroke`: `stroke`, or points +/// when `stroke` rounds the narrowest width to 0. +fn sliver_unit(stroke: vectorcraft_doc::Unit) -> vectorcraft_doc::Unit { + if stroke.number(*vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE.start()) == "0" { vectorcraft_doc::Unit::Points } else { stroke } } /// Opens the parameter dialog of `command`, headed `label`, on `params` (a menu item's own values, `__params` for the @@ -283,7 +301,7 @@ fn row(command: &str, key: &str, value: &Value, setting: Setting) -> Option &'static [&'static str] { crate::addons::cutting::BRIDGES => &["width"], "object.textWrap.options" => &["offset"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset"], + "object.path.cleanUp" => &["sliverWidth"], + "select.object.hairlineSlivers" => &["width"], _ => &[], } } @@ -413,6 +433,7 @@ pub(crate) fn length_range(command: &str, key: &str) -> Option { Some(0.0..=vectorcraft_engine::MAX_COORD) } + ("object.path.cleanUp", "sliverWidth") | ("select.object.hairlineSlivers", "width") => Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE), _ => None, } } @@ -446,6 +467,7 @@ fn order(command: &str) -> &'static [&'static str] { crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], + "object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"], _ => &[], } } @@ -1157,4 +1179,17 @@ mod tests { answer_ok(&mut app); assert_eq!(fold_angle(&mut app, a), Some(-180.0)); } + + /// Hairline Slivers' widths show in the stroke unit, or in points when that unit rounds the + /// narrowest width (0.001 pt) to 0. + #[test] + fn sliver_widths_show_in_the_stroke_unit_unless_it_rounds_them_to_zero() { + use vectorcraft_doc::Unit; + assert_eq!(sliver_unit(Unit::Points), Unit::Points); + assert_eq!(sliver_unit(Unit::Millimeters), Unit::Millimeters); + assert_eq!(sliver_unit(Unit::Inches), Unit::Points); + assert!(lengths("object.path.cleanUp").contains(&"sliverWidth")); + assert!(lengths("select.object.hairlineSlivers").contains(&"width")); + assert_eq!(length_range("object.path.cleanUp", "sliverWidth"), Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE)); + } } diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 6576e17c73..1d3cb996ee 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -302,10 +302,11 @@ fn option_rows(f: &Format, o: &FormatOption, menus: &Arc, legacy: bool) - }); return vec![row(ParamKind::choice(entries.collect(), None))]; } - // Only the colour preview can keep transparency. + // Only the colour preview can keep transparency. The options stand with no caption over them; the option's label + // names the group for assistive technology. if f.id == "eps" && o.name == "transparentPreview" { let kind = ParamKind::radio(vec![("true".into(), tl!("Transparent").into()), ("false".into(), tl!("Opaque").into())], None); - return vec![Param::new(o.name, "", kind).enabled_when("previewFormat", "tiffColor")]; + return vec![Param::new(o.name, label.clone(), kind).stacked_options().enabled_when("previewFormat", "tiffColor")]; } // Type is written as glyph outlines, which need no fonts: the row is on, and never enabled. if f.id == "eps" && o.name == "embedFonts" { @@ -320,7 +321,8 @@ fn option_rows(f: &Format, o: &FormatOption, menus: &Arc, legacy: bool) - let mut rows = vec![check]; if matches!(o.name, "separateArtboards" | "useArtboards") { let all = ParamKind::radio(vec![("true".into(), tl!("All").into()), ("false".into(), tl!("Range:").into())], None); - rows.push(Param::new("all", "", all).enabled_when(o.name, true)); + // Right under the check box, with no caption over the options. + rows.push(Param::new("all", "", all).stacked_options().enabled_when(o.name, true)); rows.push(Param::new("range", "", ParamKind::text("")).hint("1-3, 5").enabled_when("all", "false")); } rows diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 9076f18d21..8656fe3bf0 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -513,6 +513,60 @@ fn eps_save_transparency_follows_the_color_preview() { assert_eq!(dialog(&mut app).bool("embedFonts"), Some(true)); } +/// The open dialog's labelled controls with their bounds, as a screen reader is told them, after a few frames of a +/// 1440x900 window. +fn labelled_controls(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> { + let ctx = app.ui_ctx.clone().unwrap(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut nodes = Vec::new(); + for _ in 0..4 { + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + nodes = crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map_or_else(Vec::new, |u| u.nodes); + } + nodes + .iter() + .filter_map(|(_, node)| { + let b = node.bounds()?; + Some((node.label()?.to_string(), egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))) + }) + .collect() +} + +/// The bounds of the control labelled `label` in `controls`, with or without a final colon. +fn control(controls: &[(String, egui::Rect)], label: &str) -> egui::Rect { + let bare = |l: &str| l.trim_end_matches(':').to_string(); + controls + .iter() + .find(|(l, _)| bare(l) == bare(label)) + .map(|(_, r)| *r) + .unwrap_or_else(|| panic!("no control labelled {label:?} in {:?}", controls.iter().map(|(l, _)| l).collect::>())) +} + +/// The All and Range radios stand right under the artboard check box, and EPS's Transparent and Opaque radios right +/// under the Preview menu, with no empty caption over them: an empty caption leaves a band about a row tall. +#[test] +fn save_options_radios_have_no_empty_caption_over_them() { + for (picked, check) in [("art.eps", "Use Artboards"), ("art.ai", "Save each artboard to a separate file")] { + let (mut app, _, _) = desktop(picked); + save_as(&mut app, "file.saveAs"); + let controls = labelled_controls(&mut app); + let (check, all, range) = (control(&controls, check), control(&controls, "All"), control(&controls, "Range:")); + assert!(all.top() - check.bottom() <= check.height() / 2.0, "{picked}: All at {all:?}, the check box at {check:?}"); + assert!(range.top() - all.bottom() <= all.height() / 2.0, "{picked}: Range at {range:?}, All at {all:?}"); + if picked == "art.eps" { + let transparent = control(&controls, "Transparent"); + // The Preview menu: the nearest control so named above the radios (the window has other Preview controls). + let preview = controls + .iter() + .filter(|(l, r)| l.trim_end_matches(':') == "Preview" && r.bottom() <= transparent.top()) + .map(|(_, r)| *r) + .max_by(|a, b| a.bottom().total_cmp(&b.bottom())) + .expect("the Preview menu above Transparent"); + assert!(transparent.top() - preview.bottom() <= check.height() / 2.0, "Transparent at {transparent:?}, Preview at {preview:?}"); + } + } +} + #[test] fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() { let (mut app, written, _) = desktop("original.vectorcraft"); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index b2757b3cbd..ff2f1b20d6 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -299,7 +299,17 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec c("Divide Objects Below", "object.path.divideObjectsBelow"), c("Split Into Grid…", "object.path.splitIntoGrid"), Sep, - cp("Clean Up…", "object.path.cleanUp", json!({"strayPoints": true, "unpaintedObjects": true, "emptyTextPaths": true})), + cp( + "Clean Up…", + "object.path.cleanUp", + json!({ + "strayPoints": true, + "unpaintedObjects": true, + "emptyTextPaths": true, + "hairlineSlivers": false, + "sliverWidth": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH + }), + ), ], ), sub("Shape", vec![c("Convert to Shape", "object.shape.convertToShape"), c("Expand Shape", "object.expandShape")]), @@ -580,6 +590,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec c("Clipping Masks", "select.object.clippingMasks"), c("Slices", "select.object.slices"), c("Stray Points", "select.object.strayPoints"), + cp("Hairline Slivers…", "select.object.hairlineSlivers", json!({"width": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH})), c("Open Paths", "select.object.openPaths"), c("Not Aligned to Pixel Grid", "select.object.notAlignedToPixelGrid"), Sep, diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 56cdff25ac..4210c27dd1 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -46,6 +46,8 @@ pub enum PanelDrag { pub struct SwatchRows { /// The document whose rows the drag started on. pub document: u64, + /// The document's revert count: rows held across File › Revert name swatches of contents that are gone. + pub reverts: u64, pub grabbed: String, pub names: Vec, /// The names are colour groups. @@ -93,13 +95,24 @@ impl PanelDrag { } } + /// Whether the drag carries swatch rows of `current` (`(uid, reverts)` of the active document) from before + /// File › Revert: their names may now stand for other swatches, so a drop of them applies nothing. + pub(crate) fn stale_rows(&self, current: Option<(u64, u64)>) -> bool { + matches!(self, Self::Paint { rows: Some(r), .. } if current.is_some_and(|(uid, reverts)| uid == r.document && reverts != r.reverts)) + } + /// A named process swatch follows the source drawing's swatch. In another drawing its - /// captured process color applies without using a same-name swatch there. - pub(crate) fn paint_drop_params(&self, destination: Option) -> Option { + /// captured process color applies without using a same-name swatch there. Swatch rows of the destination's + /// contents from before File › Revert apply nothing. + pub(crate) fn paint_drop_params(&self, destination: Option<(u64, u64)>) -> Option { + if self.stale_rows(destination) { + return None; + } let Self::Paint { paint, params, rows, .. } = self else { return None }; if params.is_null() { return None; } + let destination = destination.map(|d| d.0); if let Some(rows) = rows.as_ref().filter(|rows| rows.unlinked_process_color) && destination.is_some_and(|uid| uid != rows.document) && let Some(color) = paint.color() diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index cdf512f078..f41407b29d 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -754,12 +754,13 @@ pub(crate) fn proxy(app: &mut VectorcraftApp, ui: &mut Ui) { }; let wells = [well(tl!("Fill"), &fill, mixed.0), well(tl!("Stroke"), &stroke, mixed.1).ring(true)]; let active = if app.session.fill_active { Well::Primary } else { Well::Secondary }; + let current = app.session.active().map(|st| (st.uid, st.reverts)); let out = SwatchPair::new(tl!("Fill and Stroke"), wells, Bind::given(active)) .swap_button(tl!("Swap Fill and Stroke")) .default_button(tl!("Default Fill and Stroke")) .popover(false) .drags([Some(PanelDrag::paint(fill)), Some(PanelDrag::paint(stroke))]) - .accepts(move |well, drag| takes_drop(mixed, well, drag)) + .accepts(move |well, drag| takes_drop(mixed, well, drag) && !drag.stale_rows(current)) .show(ui); proxy_events(app, &out); if let Some((well, drag)) = &out.dropped { @@ -813,7 +814,7 @@ fn drop_paint(app: &mut VectorcraftApp, well: Well, drag: &PanelDrag) { app.status(tl!("A linked color swatch can only be applied in its own document.")); return; } - if let Some(params) = drag.paint_drop_params(destination) { + if let Some(params) = drag.paint_drop_params(app.session.active().map(|st| (st.uid, st.reverts))) { let cmd = if well == Well::Primary { "paint.setFill" } else { "paint.setStroke" }; app.run(cmd, params).ok(); } @@ -1125,6 +1126,51 @@ mod tests { assert_eq!(current_paints(&app).0.color().map(|c| c.to_hex()), Some("#00ff00".into())); } + /// A swatch row held across File › Revert and dropped on a Fill/Stroke well applies nothing to the restored + /// drawing; the same drop from the current contents still applies. + #[test] + fn a_proxy_drop_of_a_swatch_row_held_across_file_revert_applies_nothing() { + use crate::panel_drag::SwatchRows; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let name = "Held Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("proxy-swatch-drop-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + let drag = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let paint = st.doc.swatch(name).unwrap().paint.clone(); + let rows = SwatchRows { + document: st.uid, + reverts: st.reverts, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + held: Default::default(), + }; + PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None } + }; + app.run("swatch.edit", json!({"name": name, "color": "#00ff00"})).unwrap(); + let held = drag(&app); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let before = current_paints(&app).0; + let undo = app.session.active().unwrap().history.undo.len(); + drop_paint(&mut app, Well::Primary, &held); + assert_eq!(current_paints(&app).0, before, "the stale swatch row paints nothing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the stale drop makes no edit"); + + let fresh = drag(&app); + drop_paint(&mut app, Well::Primary, &fresh); + assert_eq!(current_paints(&app).0, app.session.active().unwrap().doc.swatch(name).unwrap().paint, "a fresh drag applies"); + } + #[test] fn proxy_drops_keep_the_dragged_process_color_after_switching_documents() { use crate::panel_drag::SwatchRows; @@ -1138,6 +1184,7 @@ mod tests { let paint = source.doc.swatch(name).unwrap().paint.clone(); let rows = SwatchRows { document: source.uid, + reverts: source.reverts, grabbed: name.into(), names: vec![name.into()], groups: false, @@ -1173,6 +1220,7 @@ mod tests { let paint = source.doc.swatch(name).unwrap().paint.clone(); let rows = SwatchRows { document: source.uid, + reverts: source.reverts, grabbed: name.into(), names: vec![name.into()], groups: false, @@ -1242,6 +1290,8 @@ mod tests_color_wheel_contrast; #[cfg(test)] mod tests_color_wheel_contrast_lines; #[cfg(test)] +mod tests_color_wheel_copy; +#[cfg(test)] mod tests_color_wheel_document_colors; #[cfg(test)] mod tests_color_wheel_gamut; diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 8852b6159c..7bce287424 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -439,7 +439,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let order = rows.keys(); let sel = current_sel(app, node.as_deref()); let mut selection = node.as_deref().map_or_else(Selection::default, |n| list_selection(app, n, sel)); - let document = app.session.active().map(|st| st.uid); + // The list is keyed by the document's contents: rows held across File › Revert name items of contents that are gone. + let document = app.session.active().map(|st| (st.uid, st.reverts)); let list_id = ui.scope_id().with(("appearance-rows", document)); let has = node.is_some(); // A dragged fill/stroke or effect row lights Duplicate and Delete up, also with nothing picked. diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 04bbc7e573..97a76b420f 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -641,6 +641,42 @@ fn the_selection_summary_is_reused_until_the_document_or_its_subjects_change() { assert!(fresh_summary(&mut app).mixed(&app).is_some_and(|m| !m.transparency), "the first document's again"); } +/// A fill row held across File › Revert and released on Duplicate Selected Item leaves the restored object's +/// appearance as it is; the same drag started after the revert still duplicates the row. +#[test] +fn an_appearance_row_held_across_file_revert_is_not_dropped_on_the_footer() { + use craft::ui::runtime::drag; + + let mut app = app_with_a_selected_rectangle(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let id = app.session.active().unwrap().selection.objects[0]; + let folder = vectorcraft_testkit::TempDir::new("appearance-rows-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let items = |panel: &Panel| node(&panel.app()).appearance.items.len(); + + let mut panel = Panel::new(app, show); + let hold = |panel: &mut Panel| { + let (from, to) = (panel.rect("Fill").center(), panel.rect("Duplicate Selected Item").center()); + panel.drag_hold_between(from, to); + }; + hold(&mut panel); + assert!(drag::mark(panel.ctx()).is_some(), "Duplicate Selected Item takes rows of the current contents"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({ "ids": [id.0] })).unwrap(); + panel.frame(); + let before = items(&panel); + assert!(drag::mark(panel.ctx()).is_none(), "the footer refuses rows of the contents File › Revert replaced"); + panel.release(); + assert_eq!(items(&panel), before, "the stale row duplicates nothing"); + + hold(&mut panel); + panel.release(); + assert_eq!(items(&panel), before + 1, "a drag started after the revert still duplicates the row"); +} + /// The panel's subject is the `Arc` the document holds for the selected object, a targeted group /// or a targeted layer, not a copy of it; nothing with nothing selected. #[test] diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 205a18ac05..7c1d4cfa96 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -312,6 +312,8 @@ pub(crate) struct BrushesView { pub(crate) struct BrushKey { /// The uid of the document whose brush it is: a drag from another document's panel names another brush. pub doc: u64, + /// The document's revert count: a drag held across File › Revert names a brush of contents that are gone. + pub reverts: u64, /// The brush's name, or the group's type. pub name: String, /// Whether the row is a type's group. @@ -319,15 +321,15 @@ pub(crate) struct BrushKey { } impl BrushKey { - fn brush(doc: u64, name: &str) -> Self { - Self { doc, name: name.to_string(), group: false } + fn brush((doc, reverts): (u64, u64), name: &str) -> Self { + Self { doc, reverts, name: name.to_string(), group: false } } } /// The panel's rows: a group per shown type in [`KINDS`] order, without the `hidden` types, each over its brushes of /// `shown` in library order. Of two brushes with one name only the first, the one a stroke that names it draws with, /// has a row, so row keys stay unique. -fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec> { +fn rows(doc: (u64, u64), shown: &[Shown], hidden: &[String]) -> Vec> { let first = by_name(shown); let mut rows = Vec::new(); for (ty, label) in KINDS.iter().filter(|(ty, _)| !hidden.iter().any(|h| h == ty)) { @@ -335,7 +337,7 @@ fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec if of_type.is_empty() { continue; } - rows.push(PresetRow::group(BrushKey { doc, name: ty.to_string(), group: true }, tl!(label), 0)); + rows.push(PresetRow::group(BrushKey { doc: doc.0, reverts: doc.1, name: ty.to_string(), group: true }, tl!(label), 0)); rows.extend(of_type.into_iter().map(|b| PresetRow::item(BrushKey::brush(doc, &b.name), b.name.clone(), 1))); } rows @@ -346,6 +348,7 @@ fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec #[derive(MemoProps)] struct BrushSource<'a> { uid: u64, + reverts: u64, revision: u64, #[memo_props(covered_by = "revision", reason = "a document version's brushes and resources are fixed")] doc: Option<&'a Document>, @@ -356,8 +359,11 @@ struct BrushSource<'a> { /// The panel's presets: [`rows`]; a brush moves only among those of its type, and paints its stroke preview. fn brush_source(inputs: BrushSource<'_>) -> PresetSource<'_, BrushKey> { - let fns = PresetFns::, BrushKey>::new(|s, _| rows(s.uid, s.shown, &s.hidden)) + let fns = PresetFns::, BrushKey>::new(|s, _| rows((s.uid, s.reverts), s.shown, &s.hidden)) .accepts(|s, drag, over, _| { + if (drag.grabbed.doc, drag.grabbed.reverts) != (s.uid, s.reverts) { + return false; + } let first = by_name(s.shown); over.and_then(|over| type_of(&first, over)).is_some_and(|ty| type_of(&first, &drag.grabbed) == Some(ty)) }) @@ -531,7 +537,7 @@ fn names_of(sel: &Selection, doc: u64) -> Selection { } /// The keys of the brushes `sel` names in the document `doc`. -fn keys_of(sel: &Selection, doc: u64) -> Selection { +fn keys_of(sel: &Selection, doc: (u64, u64)) -> Selection { let key = |name: &String| BrushKey::brush(doc, name); Selection::new(sel.items.iter().map(key).collect(), sel.lead.as_ref().map(key), sel.anchor.as_ref().map(key)) } @@ -558,8 +564,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let sel_brush = selected_brush(app); let highlighted = sel_brush.clone().or_else(|| current.clone()); let given = match &multi { - Some(sel) => keys_of(sel, uid), - None => highlighted.as_deref().map(|name| Selection::single(BrushKey::brush(uid, name))).unwrap_or_default(), + Some(sel) => keys_of(sel, (uid, reverts)), + None => highlighted.as_deref().map(|name| Selection::single(BrushKey::brush((uid, reverts), name))).unwrap_or_default(), }; let hidden = app.ui.brushes_view.hidden.clone(); let view = if app.ui.brushes_view.list { PresetView::List } else { PresetView::Grid }; @@ -572,7 +578,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }; let ctx = ui.ctx().clone(); let (doc, first, multi_ref, list_ref) = (doc.as_deref(), &first, multi.as_ref(), list.as_slice()); - let source = brush_source(BrushSource { uid, revision, doc, shown: &memo, hidden: hidden.clone() }); + let source = brush_source(BrushSource { uid, reverts, revision, doc, shown: &memo, hidden: hidden.clone() }); let browser = |ui: &mut Ui| { let mut state = PresetState::new(); let ctx = ctx.clone(); @@ -639,7 +645,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } PresetEvent::Menu { target, command, .. } => item_command(app, &target, &command, multi.as_ref()), - PresetEvent::Reorder(edit) => move_brush(app, &rows(uid, &memo, &hidden), first, &edit), + PresetEvent::Reorder(edit) => move_brush(app, &rows((uid, reverts), &memo, &hidden), first, &edit), PresetEvent::Dropped { at, payload, .. } => { if let (DropAt::Onto(key), Some(ids)) = (&at, payload.get::().and_then(|p| art_of(p, uid, reverts))) { crate::dialogs::brush_replace_art::replace(app, &key.name, &ids); diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 501bd051cd..cd922c895e 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -533,7 +533,8 @@ fn a_brush_dragged_onto_another_of_its_type_moves_before_it() { let mut t = Trial::new(); let app = t.app(); let st = app.session.active().unwrap(); - let order: Vec = rows(st.uid, &document_brushes(st), &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.label).collect(); + let order: Vec = + rows((st.uid, st.reverts), &document_brushes(st), &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.label).collect(); drop(app); assert_eq!(order[..4], ["3 pt. Round", "6 pt. Flat", "10 pt. Oval", "Dots"]); let undo = |t: &Trial| undo_count(&t.app()); @@ -886,8 +887,8 @@ fn rows_of_two_brushes_with_one_name_show_the_first() { let shown = by_name(&raw)["Twin"]; assert_eq!(shown.ty, "art"); assert_eq!(shown.def, got, "the first of two rows of one name is the one shown"); - let keys: Vec = rows(st.uid, &raw, &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.key).collect(); - assert_eq!(keys, [BrushKey::brush(st.uid, "Twin")], "one row, under the first one's type"); + let keys: Vec = rows((st.uid, st.reverts), &raw, &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.key).collect(); + assert_eq!(keys, [BrushKey::brush((st.uid, st.reverts), "Twin")], "one row, under the first one's type"); } /// A brush's menu acts on it alone, or on the multi-selection when the brush is one of several diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 8239244ffb..3e706b06c1 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -64,6 +64,10 @@ //! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule, //! Show Opacity, Show Hex Field, the contrast settings, Show Color Vision Preview and Show Document //! Colors are kept with the preferences (`ui.colorWheel`). +//! +//! Panel menu › Copy Color As puts the color on the clipboard as plain text (`color.format`): Hex, +//! Hex with Alpha, CSS rgb(), CSS hsl(), CSS oklch() or CMYK Values. Its items are gray without a +//! solid color, and CSS oklch() also while the active document's RGB space is not sRGB. use std::collections::HashMap; use std::hash::{Hash, Hasher}; @@ -565,10 +569,23 @@ fn items(set: &Settings, srgb: bool, current: Option) -> Vec { out } +/// The items of Copy Color As: the `color.format` notation, which also names the row +/// (`ui.colorWheel.copy.`), and the label. +fn copy_notations() -> [(&'static str, &'static str); 6] { + [ + ("hex", tl!("Hex")), + ("hexAlpha", tl!("Hex with Alpha")), + ("rgb", tl!("CSS rgb()")), + ("hsl", tl!("CSS hsl()")), + ("oklch", tl!("CSS oklch()")), + ("cmyk", tl!("CMYK Values")), + ] +} + /// The panel menu: Wheel View and Box View, and Box Channel while the box shows; Show Out-of-Gamut /// Colors; HSL Sliders and OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; Show /// Opacity and Show Hex Field; Show Contrast, Contrast For and Contrast Background; Show Color -/// Vision Preview; and Show Document Colors. +/// Vision Preview; Show Document Colors; and Copy Color As. pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { let command = |row: String| PanelRow::Command(CommandRef::new(row_id(&row))); let mut rows = vec![command("view.wheel".into()), command("view.box".into())]; @@ -589,23 +606,72 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { vec![command("contrastBackground.below".into()), command("contrastBackground.current".into())], )); rows.extend(["vision", "documentColors"].map(|row| command(row.into()))); + rows.push(PanelRow::Separator); + rows.push(PanelRow::Submenu( + Label::from(tl!("Copy Color As").to_string()), + copy_notations().into_iter().map(|(notation, _)| command(format!("copy.{notation}"))).collect(), + )); rows } -/// The labels, checks and enabled states of [`menu_rows`]. +/// The labels, checks and enabled states of [`menu_rows`]. The items of Copy Color As are gray +/// without a solid color, and CSS oklch() also while the active document's RGB space is not sRGB. pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { - for item in items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), target_now(app).color()) { + let srgb = cms::active().rgb_is_srgb(); + for item in items(&app.ui.color_wheel, srgb, target_now(app).color()) { let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked); if let Some(hint) = item.hint { state = state.hint(hint); } states.set(CommandRef::new(row_id(&item.id)), state); } + let has_color = target_now(app).color().is_some(); + for (notation, label) in copy_notations() { + let oklch = notation == "oklch"; + let mut state = CommandState::new().title(label.to_string()).enabled(has_color && (srgb || !oklch)); + if oklch { + state = state.hint(tl!("OKLCH needs sRGB as the working RGB space").to_string()); + } + states.set(CommandRef::new(row_id(&format!("copy.{notation}"))), state); + } +} + +/// Copy Color As: put `color.format`'s text in `notation` of the color the panel shows on the +/// clipboard, with the opacity of what the row of Show Opacity edits when it has one, and say in +/// the status bar what was copied. Without a solid color nothing is copied and the answer is +/// null; an error of `color.format` goes to the status bar. Without a window to copy through, +/// nothing is copied and the status bar stays as it was, and the answer still holds the text. +/// → `{text}`. +pub(crate) fn copy_color_as(app: &mut VectorcraftApp, notation: &str) -> Result { + let tgt = target_now(app); + let Some(color) = tgt.color() else { return Ok(Value::Null) }; + let (o, live) = shown_opacity(app, &tgt); + let mut p = json!({ "color": color_json(&color), "notation": notation }); + if live { + p["opacity"] = json!(f64::from(o.clamp(0.0, 1.0)) * 100.0); + } + match app.run("color.format", p) { + Ok(r) => { + let text = r["text"].as_str().unwrap_or_default().to_string(); + let Some(ctx) = &app.ui_ctx else { return Ok(json!({ "text": text })) }; + ctx.copy_text(text.clone()); + app.status(format!("Copied the color as {text}")); + Ok(json!({ "text": text })) + } + Err(e) => { + app.status(e.clone()); + Err(e) + } + } } /// Run the menu row `id` (`ui.colorWheel.`); `None` when it is not one of this panel's. pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option> { let row = id.strip_prefix("ui.colorWheel.")?; + if let Some(notation) = row.strip_prefix("copy.") { + let (notation, _) = copy_notations().into_iter().find(|(n, _)| *n == notation)?; + return Some(copy_color_as(app, notation)); + } let current = target_now(app).color(); if row == "contrastBackground.current" && current.is_none() { return Some(Err("Current Color needs a solid color in the active proxy".to_string())); diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index ce32696fce..c75d2f7c80 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -846,7 +846,9 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra open_popover(app, request.index, at); } // A colour swatch dropped on the slider: a global or spot colour (or a tint of one) stays linked. + // Swatch rows held across File › Revert change no stop. if let Some((place, drag)) = &out.dropped + && !drag.stale_rows(app.session.active().map(|st| (st.uid, st.reverts))) && let Some(c) = drag.color() { let link = match drag { diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 76b17c33be..c102a1ecdc 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -56,10 +56,11 @@ use crate::panel_drag::PanelDrag; /// A style of the panel: its name, which is unique in a document. pub(crate) type StyleKey = String; -/// A document's graphic style dragged out to the canvas. +/// A document's graphic style dragged out to the canvas. `reverts` identifies the contents it came from. #[derive(Clone, Debug)] pub(crate) struct StyleDrag { pub(crate) document: u64, + pub(crate) reverts: u64, pub(crate) name: StyleKey, } @@ -481,8 +482,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (alt, linked) = (alt_held(ui), app.session.selection_graphic_style().is_some()); let thumbs = style_thumbs(app, &doc, &looks, panel.preview); let source = style_source(thumbs); - // The browser's own state (an open rename field, the scroll position) is kept per document. - let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid)); + // The browser's own state (an open rename field, the scroll position) is kept per document contents: a style + // dragged from contents File › Revert replaced is not this list's. + let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid, reverts)); let list = PresetBrowser::::list_id(browser_id); let takes_object = move |drag: &PanelDrag, _: &DropAt| dropped_object(drag, uid, reverts).is_some(); // A style dragged from this panel's list. @@ -524,16 +526,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .selection(Bind::bound(&mut panel.selection)) .view_lock(view.preset_view()) .reorder(PresetReorder::items()) - .drag_payload(move |drag: &ListDrag| Some(StyleDrag { document: uid, name: drag.grabbed.clone() })) + .drag_payload(move |drag: &ListDrag| Some(StyleDrag { document: uid, reverts, name: drag.grabbed.clone() })) .empty(tl!("Select styled art and click New Graphic Style.")) .row_items(items) .tip(|ui, key| large_tip(app, &thumbs, ui, key)) .takes_drop(PresetDrop::new::(DropPlace::Between, takes_object)) .takes_drop(PresetDrop::new::(DropPlace::Onto, takes_object)) - .takes_drop(PresetDrop::new::>( - DropPlace::Onto, - |drag, at| matches!(at, DropAt::Onto(name) if !drag.keys.contains(name)), - )) + .takes_drop(PresetDrop::new::>(DropPlace::Onto, move |drag, at| { + ours(drag) && matches!(at, DropAt::Onto(name) if !drag.keys.contains(name)) + })) .show(ui) }) }; @@ -1612,6 +1613,41 @@ mod tests { assert_eq!(names(&p.app()).len(), before.len() + 1, "a thumbnail drag started after the revert still makes a style"); } + /// A style of the list held across File › Revert and released on New Graphic Style duplicates no style of the + /// restored contents; the same drag started after the revert still duplicates it. + #[test] + fn a_style_held_across_file_revert_is_not_dropped_on_the_footer() { + use crate::tests::panel_harness::Panel as PanelHarness; + use craft::ui::runtime::drag; + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Held"})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("graphic-styles-footer-revert"); + let path = folder.join("drawing.vectorcraft"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + + let mut p = PanelHarness::new(app, show); + let hold = |p: &mut PanelHarness| { + let (from, to) = (p.rect("Held").center(), p.rect("New Graphic Style (Alt-click to name it)").center()); + p.drag_hold_between(from, to); + }; + hold(&mut p); + assert!(drag::mark(p.ctx()).is_some(), "New Graphic Style takes a style of the current contents"); + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.frame(); + let before = names(&p.app()); + assert!(drag::mark(p.ctx()).is_none(), "New Graphic Style refuses a style of the contents File › Revert replaced"); + p.release(); + assert_eq!(names(&p.app()), before, "the stale drop duplicates nothing"); + + hold(&mut p); + p.release(); + assert_eq!(names(&p.app()).len(), before.len() + 1, "a drag started after the revert still duplicates the style"); + } + /// A style dropped on another with Alt takes that style's look; on itself it does nothing. #[test] fn a_style_dropped_on_another_with_alt_replaces_that_style() { diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 62e1da73ca..d9e2f9b70d 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -205,6 +205,9 @@ impl Membership { /// The item of this library that `drag` holds, or what it would add. `library.add` reads object IDs in the current document. fn grabbed(&self, drag: &PanelDrag) -> Option { + if drag.stale_rows(self.active_document) { + return None; + } let library = &self.library; match drag { PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 9af1be9d75..b9877b53ca 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -277,6 +277,49 @@ fn a_library_drop_does_not_collect_unrelated_artwork_after_a_document_switch() { assert_eq!(graphics(&mut panel.app()).len(), 1, "artwork from the current document can still be added"); } +#[test] +fn a_library_drop_of_a_swatch_row_held_across_file_revert_adds_nothing() { + use crate::panel_drag::SwatchRows; + + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("library.create", json!({"name": "Brand"})).unwrap(); + let name = "Sunset"; + let gradient = json!({"stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]}); + app.run("swatch.new", json!({"name": name, "gradient": gradient})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("library-swatch-drop-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + let gradient = json!({"stops": [{"offset": 0, "color": "#00ff00"}, {"offset": 1, "color": "#0000ff"}]}); + app.run("swatch.edit", json!({"name": name, "paint": {"gradient": gradient}})).unwrap(); + let state = app.session.active().unwrap(); + let held = PanelDrag::Paint { + paint: state.doc.swatch(name).unwrap().paint.clone(), + params: json!({"swatch": name}), + rows: Some(SwatchRows { + document: state.uid, + reverts: state.reverts, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + held: Default::default(), + }), + library: None, + }; + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + let membership = Membership::of("Brand", app.session.libraries.get("Brand").unwrap(), Some((state.uid, state.reverts))); + assert!(membership.landing(&held, None).is_none(), "hover refuses the stale swatch row"); + let mut panel = Harness::new(app, with_source); + panel.frame(); + let at = panel.rect("This library is empty").center(); + drop_at(&mut panel, held, at); + assert!(panel.app().session.libraries.get("Brand").unwrap().gradients.is_empty(), "release adds no gradient"); +} + +#[test] fn gradients_and_patterns_come_from_swatches_and_paint_the_selection() { let mut app = app(); app.run("library.create", json!({"name": "Brand"})).unwrap(); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 5caf20c7b5..515456cad8 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -429,7 +429,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let state = &mut model.state; // The browser fills the room the footer leaves, so the footer stays in view under the swatches. The body can run // more than once in a pass, so each run builds its own browser. A list drag is keyed by its browser ID. Each - // document has its own browser. + // document's contents have their own browser, so rows held across File › Revert are not this list's. let mut footed = None; let out = Stack::new() .label(tl!("Swatches")) @@ -452,7 +452,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .search(search) .reveal(focus.clone().map(SwatchKey::Swatch)) .footer(None); - ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner + ui.push_id(("swatch-rows", document, reverts), |ui| browser.show(ui)).inner }) .inner; app.ui.swatches_panel = model; @@ -806,7 +806,8 @@ struct Footer { opts: Option, group: Option, libraries_open: bool, - document: Option, + /// The uid and revert count of the document the panel shows. + document: Option<(u64, u64)>, /// Whether a drag from the list still has rows the document holds unchanged ([`dnd::follow`]). held: bool, } @@ -822,7 +823,7 @@ impl Footer { Footer { kind: model.kind, libraries_open: library_panel::any_open::(&app.ui), - document: app.session.active().map(|state| state.uid), + document: app.session.active().map(|state| (state.uid, state.reverts)), held, sel, del, @@ -836,7 +837,8 @@ impl Footer { let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); let document = self.document; let held = self.held; - let rows_drag = move |d: &PanelDrag| held && matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); + let rows_drag = + move |d: &PanelDrag| held && matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some((rows.document, rows.reverts)) == document); let edit = if self.group.is_some() { FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) } else { diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 78ebf4a02d..df967e9700 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -8,10 +8,10 @@ use craft::ui::contract::{DropAt, ReorderMove}; use vectorcraft_color::SwatchGroup; use vectorcraft_engine::{DocState, History, HistoryEntry}; -/// Swatches take paints, and take swatch rows or canvas art from the current document. +/// Swatches take paints, and take swatch rows or canvas art from the current document's current contents. pub(super) fn accepts(drag: &PanelDrag, document: u64, reverts: u64) -> bool { match drag { - PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document, + PanelDrag::Paint { rows: Some(rows), .. } => (rows.document, rows.reverts) == (document, reverts), PanelDrag::Paint { .. } => true, _ => drag.artwork_for(document, reverts).is_some(), } @@ -72,7 +72,7 @@ pub(super) fn drag_of(start: &DragStart, key: &SwatchKey, names: Vec) -> }; let held = Arc::new(start.rows(&names)); let groups = matches!(key, SwatchKey::Group(_)); - let rows = SwatchRows { document: start.uid, grabbed: name.to_string(), names, groups, unlinked_process_color, held }; + let rows = SwatchRows { document: start.uid, reverts: start.reverts, grabbed: name.to_string(), names, groups, unlinked_process_color, held }; PanelDrag::Paint { paint, params, rows: Some(rows), library: None } } @@ -320,7 +320,7 @@ pub(super) enum FooterTarget { /// started in another document, is left alone. Other drags are left to their own targets. pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, drag: &PanelDrag) { let PanelDrag::Paint { rows: Some(r), .. } = drag else { return }; - if !app.session.active().is_some_and(|state| state.uid == r.document) { + if !app.session.active().is_some_and(|state| (state.uid, state.reverts) == (r.document, r.reverts)) { return; } let held = follow(app, r); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index dd993bb69d..f20c725ac0 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -157,6 +157,53 @@ fn a_swatch_row_drag_reorders_only_its_source_document() { assert_eq!(names_of(&panel.app(), None), before_source); } +/// Swatch rows held across File › Revert move nothing in the restored swatches, and drop nothing on New Swatch or +/// Delete Swatch; the same drag started after the revert still moves them. +#[test] +fn a_swatch_row_drag_held_across_file_revert_moves_nothing() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let folder = vectorcraft_testkit::TempDir::new("swatch-rows-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.ellipse", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap(); + let stale = rows_drag(&app, "Red", &["Red"]); + let before = names_of(&app, None); + + let mut panel = Panel::new(app, show); + let drag_red = |panel: &mut Panel| { + let red = "Red, #ed1c24"; + let from = panel.rect(red).center(); + let to = panel.rect("Green, #39b54a").center(); + panel.drag_hold_role(red, Role::LIST_ITEM, to - from); + }; + drag_red(&mut panel); + assert!(drag::mark(panel.ctx()).is_some(), "the list takes rows of the current contents"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.frame(); + assert!(drag::mark(panel.ctx()).is_none(), "the list refuses rows of the contents File › Revert replaced"); + panel.release(); + assert_eq!(names_of(&panel.app(), None), before, "the stale rows move nothing"); + + let restored = doc(&panel.app()); + let undo = undo_steps(&panel.app()); + for target in [dnd::FooterTarget::New, dnd::FooterTarget::Delete] { + dnd::on_footer_drop(&mut panel.app(), target, &stale); + assert_eq!(doc(&panel.app()), restored); + assert_eq!(undo_steps(&panel.app()), undo); + assert!(!dialog_open(&panel.app(), crate::dialogs::confirm::KIND)); + } + + drag_red(&mut panel); + panel.release(); + assert_ne!(names_of(&panel.app(), None), before, "a drag started after the revert still moves the rows"); +} + #[test] fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 11f805bad5..c257f30d0a 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -58,6 +58,8 @@ fn thumb_px(size: f32, pixels_per_point: f32) -> u32 { pub(crate) struct SymbolKey { /// The uid of the document whose Symbols panel showed the symbol. pub doc: u64, + /// The document's revert count: a drag held across File › Revert names a symbol of contents that are gone. + pub reverts: u64, /// The symbol's name. pub name: String, } @@ -496,6 +498,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { #[derive(MemoProps)] struct SymbolSource<'a> { uid: u64, + reverts: u64, revision: u64, #[memo_props(covered_by = "revision", reason = "a document version's symbols are fixed")] doc: &'a Document, @@ -506,7 +509,11 @@ struct SymbolSource<'a> { /// The panel's presets: a row per symbol of the document, in its order, each with its thumbnail. fn symbol_source(inputs: SymbolSource<'_>) -> PresetSource<'_, SymbolKey> { let fns = PresetFns::, SymbolKey>::new(|s, _| { - s.doc.symbols.iter().map(|sym| PresetRow::item(SymbolKey { doc: s.uid, name: sym.name.clone() }, sym.name.clone(), 0)).collect() + s.doc + .symbols + .iter() + .map(|sym| PresetRow::item(SymbolKey { doc: s.uid, reverts: s.reverts, name: sym.name.clone() }, sym.name.clone(), 0)) + .collect() }) .thumb(|s, cx, rect, info| paint_symbol(cx, rect, s.doc, s.keys, &info.key.name)); PresetSource::new(inputs, fns) @@ -540,8 +547,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let marked = marked(app); let inst = has_instances_selected(app); let linked = linked_symbols(app); - let key = |name: &str| SymbolKey { doc: uid, name: name.to_string() }; - let source = symbol_source(SymbolSource { uid, revision, doc: &doc, keys: &keys }); + let key = |name: &str| SymbolKey { doc: uid, reverts, name: name.to_string() }; + let source = symbol_source(SymbolSource { uid, reverts, revision, doc: &doc, keys: &keys }); // The symbols drawn selected: the ones Select All Unused picked, which further picks change, // else the current one. let (mut selection, select) = if marked.is_empty() { @@ -552,8 +559,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (view, zoom) = app.ui.symbols_view.preset(); let browser_id = ui.make_persistent_id("symbols-browser"); let list = PresetBrowser::::list_id(browser_id); - // A symbol dragged from this panel's list, of the document it shows. - let ours = move |drag: &ListDrag| drag.list == list && drag.grabbed.doc == uid; + // A symbol dragged from this panel's list, of the contents of the document it shows. + let ours = move |drag: &ListDrag| drag.list == list && (drag.grabbed.doc, drag.grabbed.reverts) == (uid, reverts); let svg = |name: &'static str| IconSpec::svg(IconId::new(name)); let actions = [ FooterAction::new(svg("library"), tl!(SymbolLibraries::MENU)) @@ -656,7 +663,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(out) = footer else { return }; match &out.dropped { Some(dropped) => { - let Some(drag) = dropped.payload::>() else { return }; + // A symbol of other contents, another document's or the ones File › Revert replaced, drops nothing. + let Some(drag) = dropped.payload::>().filter(|drag| ours(drag)) else { return }; let name = &drag.grabbed.name; // A symbol deleted while it was dragged drops nothing. if !doc.symbols.iter().any(|s| s.name == *name) { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_copy.rs b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs new file mode 100644 index 0000000000..84001223ab --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs @@ -0,0 +1,219 @@ +//! The Color Wheel panel's Copy Color As: the text each item puts on the clipboard, the opacity it +//! carries, the status bar message, and that `color.parse` reads each text back. + +use craft::keymap::CommandRef; +use craft::ui::menu::PanelRow; +use craft::ui::runtime::commands::{CommandState, CommandStates}; +use serde_json::{Value, json}; +use vectorcraft_color::cms; +use vectorcraft_engine::Session; + +use super::color_wheel::{menu_rows, menu_states, run}; +use crate::VectorcraftApp; + +/// The command ids of Copy Color As's items, in the menu's order. +const ITEMS: [&str; 6] = [ + "ui.colorWheel.copy.hex", + "ui.colorWheel.copy.hexAlpha", + "ui.colorWheel.copy.rgb", + "ui.colorWheel.copy.hsl", + "ui.colorWheel.copy.oklch", + "ui.colorWheel.copy.cmyk", +]; + +/// An app with a selected rectangle filled with #336699 at `opacity` %. +fn app(opacity: f64) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#336699", "opacity": opacity})).unwrap(); + app +} + +/// Run Copy Color As › `notation` in one frame: its answer and the texts it put on the clipboard. +fn copy(app: &mut VectorcraftApp, notation: &str) -> (Result, Vec) { + let ctx = crate::testing::ui_context(); + let mut answer = None; + let out = + crate::testing::part_frame(app, &ctx, Default::default(), |app, _| answer = run(app, &format!("ui.colorWheel.copy.{notation}"), &json!({}))); + let copied = + out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }).collect(); + (answer.expect("a Copy Color As item"), copied) +} + +/// The texts Copy Color As › `notation` puts on the clipboard. +fn copied(app: &mut VectorcraftApp, notation: &str) -> Vec { + copy(app, notation).1 +} + +fn undo_count(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// Whether the panel menu's command `id` is enabled. +fn enabled(app: &VectorcraftApp, id: &str) -> bool { + let mut states = CommandStates::new(); + menu_states(app, &mut states); + states.get(&CommandRef::new(id.to_string())).is_some_and(CommandState::is_enabled) +} + +/// Copy Color As › CSS rgb() puts CSS Color 4's space-separated form on the clipboard, with the +/// opacity after a slash, answers it and says what it copied; the document does not change. +#[test] +fn css_rgb_copies_the_color_and_the_opacity() { + let mut app = app(50.0); + let before = undo_count(&app); + let (answer, texts) = copy(&mut app, "rgb"); + assert_eq!(texts, ["rgb(51 102 153 / 50%)"]); + assert_eq!(answer, Ok(json!({"text": "rgb(51 102 153 / 50%)"}))); + assert_eq!(app.ui.status, "Copied the color as rgb(51 102 153 / 50%)"); + assert_eq!(undo_count(&app), before, "copying records no undo step"); +} + +/// Without a window to copy through, an item answers its text and the status bar does not say it +/// was copied. +#[test] +fn without_a_window_the_text_is_answered_and_not_reported_as_copied() { + let mut app = app(50.0); + app.ui_ctx = None; + app.ui.status.clear(); + assert_eq!(run(&mut app, "ui.colorWheel.copy.hex", &json!({})), Some(Ok(json!({"text": "#336699"})))); + assert_eq!(app.ui.status, ""); +} + +/// Hex and CMYK Values never carry the opacity; Hex with Alpha always does, as `ff` at 100 %; CSS +/// adds it only under 100 %. +#[test] +fn each_item_writes_its_notation() { + let mut half = app(50.0); + assert_eq!(copied(&mut half, "hex"), ["#336699"]); + assert_eq!(copied(&mut half, "hexAlpha"), ["#33669980"]); + assert_eq!(copied(&mut half, "hsl"), ["hsl(210 50% 40% / 50%)"]); + let oklch = copied(&mut half, "oklch"); + assert!(oklch[0].starts_with("oklch(") && oklch[0].ends_with(" / 50%)"), "{oklch:?}"); + let mut full = app(100.0); + assert_eq!(copied(&mut full, "hexAlpha"), ["#336699ff"]); + assert_eq!(copied(&mut full, "rgb"), ["rgb(51 102 153)"]); + let cmyk = copied(&mut full, "cmyk"); + assert_eq!(copied(&mut half, "cmyk"), cmyk, "CMYK Values leaves the opacity out"); + // The working CMYK numbers through the color settings, as color.convert gives them. + let r = full.run("color.convert", json!({"color": "#336699", "to": "cmyk"})).unwrap(); + let pct: Vec = r["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect(); + assert_eq!(cmyk, [format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3])]); +} + +/// A CMYK fill copies its own CMYK values. +#[test] +fn a_cmyk_fill_copies_its_own_values() { + let mut app = app(100.0); + app.run("paint.setFill", json!({"color": {"c": 10, "m": 20, "y": 30, "k": 0}})).unwrap(); + assert_eq!(copied(&mut app, "cmyk"), ["C=10 M=20 Y=30 K=0"]); +} + +/// `color.parse` reads every copied text but CMYK Values back to the color the hex field shows, +/// and the alpha to the fill's opacity. +#[test] +fn color_parse_reads_each_copied_text_back() { + let mut app = app(25.0); + for notation in ["hex", "hexAlpha", "rgb", "hsl", "oklch"] { + let text = copied(&mut app, notation).pop().unwrap(); + let r = app.run("color.parse", json!({"text": text})).unwrap(); + assert_eq!(r["hex"], "#336699", "{notation}: {text}"); + let opacity = r["opacity"].as_f64(); + match notation { + "hex" => assert_eq!(opacity, None, "{text}"), + // 64 of 255. + "hexAlpha" => assert_eq!(opacity, Some(25.1), "{text}"), + _ => assert_eq!(opacity, Some(25.0), "{text}"), + } + } +} + +/// With nothing selected the panel shows the color for new art, which has no opacity of its own: +/// the copied text carries none. +#[test] +fn with_nothing_selected_the_color_for_new_art_is_copied_without_an_opacity() { + let mut app = app(50.0); + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"color": "#336699"})).unwrap(); + assert_eq!(copied(&mut app, "hexAlpha"), ["#336699ff"]); + assert_eq!(copied(&mut app, "rgb"), ["rgb(51 102 153)"]); +} + +/// Without a solid color (a fill of None) nothing is copied, the status bar stays as it was and +/// the item answers null. +#[test] +fn nothing_is_copied_without_a_solid_color() { + let mut app = app(100.0); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.ui.status.clear(); + let (answer, texts) = copy(&mut app, "hex"); + assert!(texts.is_empty()); + assert_eq!(answer, Ok(Value::Null)); + assert_eq!(app.ui.status, ""); +} + +/// The panel menu ends with a separator and the Copy Color As submenu, which holds the six items in +/// order; another `copy.` row is not one of the panel's. +#[test] +fn the_menu_ends_with_copy_color_as() { + let mut app = app(100.0); + let rows = menu_rows(&app); + let [.., PanelRow::Separator, PanelRow::Submenu(_, items)] = &rows[..] else { panic!("Copy Color As last: {} rows", rows.len()) }; + let ids: Vec = items + .iter() + .map(|row| match row { + PanelRow::Command(c) => c.key().to_string(), + _ => panic!("a command row"), + }) + .collect(); + assert_eq!(ids, ITEMS); + assert!(run(&mut app, "ui.colorWheel.copy.lab", &json!({})).is_none()); +} + +/// The items of Copy Color As are gray without a solid color and available with one. +#[test] +fn copy_color_as_is_gray_without_a_solid_color() { + let app = app(100.0); + for id in ITEMS { + assert!(enabled(&app, id), "{id}"); + } + let mut none = self::app(100.0); + none.run("paint.setFill", json!({"none": true})).unwrap(); + for id in ITEMS { + assert!(!enabled(&none, id), "{id}"); + } +} + +/// While the working RGB space is not sRGB, Copy Color As › CSS oklch() is gray, the other items are +/// not, and copying as oklch() puts the error in the status bar and nothing on the clipboard. +#[test] +fn css_oklch_is_gray_while_the_working_space_is_not_srgb() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_COPY_P3"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "panels::tests_color_wheel_copy::css_oklch_is_gray_while_the_working_space_is_not_srgb", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated working space test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let mut app = app(100.0); + assert!(enabled(&app, "ui.colorWheel.copy.oklch"), "sRGB"); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + let (answer, texts) = copy(&mut app, "oklch"); + assert!(texts.is_empty()); + assert!(answer.is_err(), "{answer:?}"); + assert!(app.ui.status.ends_with("OKLCH needs sRGB as the working RGB space"), "{}", app.ui.status); + assert!(!enabled(&app, "ui.colorWheel.copy.oklch")); + for id in ITEMS.into_iter().filter(|id| !id.ends_with("oklch")) { + assert!(enabled(&app, id), "{id}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 8a368ddcdf..bb5f85d641 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -721,7 +721,6 @@ saturation and lightness (0 to 100 %) of the color's display sRGB, as CSS Color `color.convert {"color": "#ff0000", "to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. A color outside sRGB (a Lab or CMYK color, an RGB color in a wider RGB space, or RGB numbers past 0 to 1) is clipped to sRGB first. -The answer of `ui.colorWheel` and the settings also carry `sliders`. `ui.colorWheel {"vision": true}` turns on the Color Wheel panel's Show Color Vision Preview, as its panel menu does: a row of four chips under the wheel or the box shows the current color through the protanopia, deuteranopia @@ -755,13 +754,33 @@ angles and `none`, so `calc()`, `var()`, `color-mix()`, relative color syntax an errors, as are named colors and the functions and color spaces not listed above (`hwb()`, `lab()`, `oklab()` and `color()`). A hex color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as `#rrggbb` does in every command, and `oklch()` gives its sRGB color, with the chroma lowered to fit sRGB as OKLCH -Sliders lower it; `oklch()` is an error while the working RGB space is not sRGB. Values are clamped where CSS clamps +Sliders lower it; `oklch()` is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB. Values are clamped where CSS clamps them when it parses them (red, green and blue to 0 to 255, the alpha to 0 to 1, a negative saturation to 0, OKLCH lightness to 0 to 1 and a negative chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is clipped. An `hsl()` color whose saturation and lightness are so large that a channel overflows to an infinity is an error. `opacity` is the alpha as a percentage, or `null` when the text gives none. Any other text is an error. The color parameters of the other commands still refuse `#rrggbbaa` and `#rgba`. +`color.format {"color": "#336699", "opacity": 50, "notation": "rgb"}` answers `{"text": "rgb(51 102 153 / 50%)"}`. +`notation` is `hex` (`#336699`), `hexAlpha` (`#33669980`, and `#336699ff` at 100 % or without `opacity`), `rgb`, `hsl` +(`hsl(210 50% 40% / 50%)`), `oklch` (`oklch(49.93% 0.0987 250.43 / 50%)`) or `cmyk` (`C=87 M=61 Y=19 K=0` with the +default color settings). The CSS forms are space-separated and add ` / opacity%` when the opacity, rounded to two decimal places, is under 100 (`99.999` writes no suffix); +`hex` and `cmyk` leave the opacity out. Every notation but `cmyk` writes the working RGB numbers, the same numbers +the Color panel's hex field shows, with lowercase hex digits; `oklch` is an error while the working RGB space is not +sRGB. `hsl()` and `oklch()` give their numbers to two decimal places (chroma to four), and `oklch()` takes up to two +more where fewer would read back to another color. `cmyk` is the color in the working CMYK space +through the color settings, written as a new swatch is named; a CMYK color keeps its own values. `color.parse` reads +every notation but `cmyk` back to the same `#rrggbb`. `opacity` is 0 to 100, and any other value, or another +`notation`, is an error. + +The Color Wheel panel menu's Copy Color As puts the panel's color on the clipboard as Hex, Hex with Alpha, CSS +rgb(), CSS hsl(), CSS oklch() or CMYK Values, the six `color.format` notations, with the opacity that Show Opacity +edits when it has one (whether or not that row shows), and the status bar shows what was copied. Its items are the +menu commands `ui.colorWheel.copy.hex`, `ui.colorWheel.copy.hexAlpha`, `ui.colorWheel.copy.rgb`, +`ui.colorWheel.copy.hsl`, `ui.colorWheel.copy.oklch` and `ui.colorWheel.copy.cmyk`, which answer `{text}`, or null without a solid color. They are gray without a solid color, and CSS oklch() is also gray +while the active document's RGB space is not sRGB. Without a window to copy through, an item puts nothing on the clipboard and +leaves the status bar as it was, and still answers `{text}`. + In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) @@ -974,7 +993,7 @@ its own. A color for a grayscale or 1-bit image's drawing color creates no fill to a fill row the image has. With New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included. Without a new paint, `objects` counts only the targets that took the opacity. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has that row (a selected path of a compound path answers with its compound path's row, which the commands edit, and a -selected Live Paint group answers with its faces' fills and its edges' strokes). It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket paints (it is the active tool, or a Cmd+click or an Eyedropper pick works for it), +selected Live Paint group answers with its faces' fills and its edges' strokes). With a layer targeted, it reads the layer's visible, unlocked art, as the commands do. It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket paints (it is the active tool, or a Cmd+click or an Eyedropper pick works for it), while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and @@ -6071,7 +6090,8 @@ Their OK runs `brush.new {type, name, params, ids?}`, and Cancel adds no brush. `brush.placeArt {name, x?, y?}` places a copy of the art a scatter, art or pattern brush is made of, centered on (`x`, `y`) (default: the center of the first artboard), and selects it, in one undo step. The app runs it when a brush is dragged from the Brushes panel onto an empty part of the canvas; dropped on a path, a brush is applied to it -(`brush.apply`). A pattern brush places its tiles left to right, 10 pt apart, in the order side, outer corner, inner +(`brush.apply`). A brush, graphic style, symbol, swatch or appearance whose drag started before File › Revert is not +dropped on the restored drawing. A pattern brush places its tiles left to right, 10 pt apart, in the order side, outer corner, inner corner, start, end (only the tiles it has art for), each in a group named Side Tile, Outer Corner Tile, Inner Corner Tile, Start Tile or End Tile. A tile with a repeat frame has an unpainted rectangle at the back of its group that marks the frame. A symbol instance in the art is measured by its symbol's art. A calligraphic or bristle brush is refused @@ -7219,7 +7239,8 @@ the panel shows) is meant. takes them), `fillColor` / `strokeColor` (the first selected object's solid colour, else the default one, or `color`), `charStyle` / `paraStyle` (the selected text's attributes). The new item goes into `group` (by default into none) and, with `before` or `after` (another item of its kind), just before or after that item, as `library.moveItem` places one; -art and swatches dropped among the panel's items are added this way. An item the library already has is reported as +art and swatches dropped among the panel's items are added this way (a swatch dragged before File › Revert of its +drawing is not added). An item the library already has is reported as `existing`, and stays where it is. `library.use {library?, kind, item, center?, to?}` uses one: a graphic is placed centred on `center` (pasted with its resources; a swatch name the document gives another colour merges into the document's), a colour paints the selection's fill or stroke, and a style is added @@ -8478,6 +8499,25 @@ the dialog on those settings next time. `"joins": 3`, `"rows": "many"` or `"addGuides": "yes"`, and change nothing. A distance still takes a string with a unit (`"5 mm"`). `joins` must be `miter`, `round` or `bevel`. Omitting a param or giving null keeps its default. +`object.path.cleanUp` with `hairlineSlivers: true` also removes hairline slivers: closed paths and compound paths with +a visible fill, no visible stroke and no effect, so thin that no circle `sliverWidth` across fits inside their fill +(Unpainted Objects covers shapes with no paint). A compound path is measured as one fill, so a compound path with one +sliver member and one real shape stays. `sliverWidth` is a distance from 0.001 to 3 pt; it defaults to 0.03 mm, +VectorCraft's own value, and `hairlineSlivers` is off by default. In the desktop app the Clean Up dialog has a Hairline +Slivers checkbox and a Sliver Width field, shown in the stroke unit, or in points when that unit's field would round +0.001 pt to 0. `select.object.hairlineSlivers {width?}` (Select › Object › Hairline Slivers…) selects the objects Clean +Up would remove, only inside the isolated group while one is isolated, and replies `{count, warning?}`. Neither command +takes hidden or locked objects, objects at 0% opacity or in a group or layer at 0% opacity, objects in template +layers, art on locked artboards, guides, the clipping paths of groups and layers, what a group or compound path used as +a clipping path holds, shapes with an effect, or the members of Live Paint groups and other live or generated art. A shape +that holds a circle 15/16 of the width across is kept too. A shape too complex to measure is kept as well, and so is +every shape still unmeasured when one run reaches its limit of work; the reply's `warning` says how many there were: + +```json +{"name":"run_command","arguments":{"command":"object.path.cleanUp","params":{"strayPoints":false,"unpaintedObjects":false,"emptyTextPaths":false,"hairlineSlivers":true,"sliverWidth":"0.03 mm"}}} +{"name":"run_command","arguments":{"command":"select.object.hairlineSlivers","params":{"width":0.1}}} +``` + ## Smooth `object.path.smooth` smooths the selected paths (or the objects in `ids`), compound path members included, as one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50fd2f27cd..152022114c 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 - **Geometry and effects:** - **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged. - Pathfinder (10 exact curve booleans; single-result shape operations retain source names and SVG IDs, #1293), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. With one group selected alone, the Pathfinder panel's buttons work on its members (among other selected objects a group still acts as one shape), and a greyed-out button says what it needs (#1450; behaviour reference: [combine objects using Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html); one plain path selected alone stays disabled, which the documentation doesn't settle). Split Into Grid takes the number, height or width, gutter and total of the rows and of the columns, Add Guides and Preview, and several selected paths become one grid painted as the topmost one (#1462, `object.path.splitIntoGrid`; behaviour reference: [divide or split objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/divide-or-split-objects.html); a typed height or width keeps the gutter and changes the total, our choice). Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart. In the Pathfinder panel a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled (#1642, #1635). + Clean Up has a Hairline Slivers option, VectorCraft's own and off by default: it removes closed paths and compound paths with a visible fill, no visible stroke and no effect when no circle as wide as its Sliver Width (0.03 mm by default) fits inside their fill, and Select › Object › Hairline Slivers… selects them (`crates/engine/src/tests/pathops.rs`, `crates/pathops/src/thickness.rs` tests). Outline Stroke, Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the object's visible geometry effects (Offset Path, Zig Zag and the others) to the path, and then apply each stroke's own geometry effects before outlining that stroke, as the canvas draws it. The filled outline of a stroke without a brush keeps the stroke's other effects, such as a drop shadow. Outline Stroke and Unite remove the overlaps of a long, low path with the sweep turned along it: when the estimated number of segments the sweep holds at once is under two thirds as large for the path turned a quarter turn (paths of 2,048 segments or more), the overlaps are removed on the turned path and the result is turned back, which moves no point by rounding. The lookups of the input curve that a piece of the result lies on, and of the input anchors that are kept, can search along y instead of x: once lookups with more than 64 candidates along x have counted 16 for each input curve or anchor, a lookup searches along y when it finds fewer candidates there (under a quarter as many for curves), and where that has rarely happened it measures along y in only one lookup of 32. On one open path of 200,000 anchors in rows of 1,000, Outline Stroke takes 17.3 s of processor time instead of 31.3 s and Unite 2.9 s instead of 6.5 s in a release build. A turned result has as many subpaths as the result without the turn, and the area where the two differ is no larger than the refit precision times the outline's length (`crates/pathops/src/sweep_axis.rs` tests). Offset Path turns the sweep the same way: when the estimate for its fill, the ring stroked around the fill and the outline of its open subpaths is under two thirds as large turned a quarter turn, the faces are found on the turned parts, the faces that lie within the offset distance of the path are dropped by testing their points turned back, and the result is turned back. On an open path of 10,000 anchors in rows of 1,000, offsetting by 2 pt takes 1.0 s of processor time instead of 1.8 s in a release build. The offset of a long, low path has as many subpaths as the offset of the same path stood on end, and the area where the two differ is no larger than the refit precision times the outline's length (`offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end`). @@ -2154,7 +2155,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **HSL Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item HSL Sliders (`ui.colorWheel {sliders: "hsl"}`, kept with the preferences) shows H, S and L rows in place of OKLCH Sliders that edit the color by the hue (0 to 360°), saturation and lightness (0 to 100 %) of its display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes from display sRGB into the working RGB space as the wheel's picks do, and the rows keep the hue of a gray. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. Evidence: `hsl_follows_css_color_4` and `hsl_roundtrip` in `crates/color/src/lib.rs`; the HSL tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `a_gray_keeps_the_hsl_hue_it_was_given` among them. Scores and estimates are unchanged. - **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged. - VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`; `oklch()` only while the active document's RGB space is sRGB), and `color.parse` reads every form but the CMYK values back to the same color. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.rs`. Scores and estimates are unchanged. The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics (AA only for graphics). `color.contrast` answers the same for agents. The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics (AA only for graphics). `color.contrast` answers the same for agents. With the row shown, the wheel's square and the box's field draw the AA and AAA lines, and a chip in the row offers the closest color of the same hue that passes, which `color.contrast` answers as `fix`. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).